Skip to content

Commit 265f4dd

Browse files
fcgithclaude
andcommitted
fix(cursor): read usage limits with the instance's own login
Cursor browser sign-ins could not publish plan limits. The usage probe short-circuited those keys and relied on host CLI credentials. Distinguish absent, valid, and expired stored instance credentials. Exchange stored instance keys and read usage at their HTTPS backend origin without redirects. Cache tokens by instance and key hash, coalesce exchanges, and retry one cached-token 401. Preserve host fallback only for absent credentials and keep failures free of secrets. Env CURSOR_API_KEY behavior is unchanged. Enterprise pooled usage (teamId/includePooledUsage), usage history, shared aggregation, and UI changes remain out of scope; both request bodies remain {}. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 9c16146 commit 265f4dd

6 files changed

Lines changed: 631 additions & 13 deletions

File tree

‎packages/provider-cursor/src/server/auth.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,25 @@ const phase = (auth: Auth, phase: ProviderAuthState["phase"], session = owner) =
8080
);
8181

8282
it.layer(NodeServices.layer)("CursorAuth", (it) => {
83+
it.effect("distinguishes absent, valid and expired stored credentials", () =>
84+
Effect.gen(function* () {
85+
const harness = yield* makeHarness();
86+
expect(yield* harness.auth.readCredentialState).toEqual({ status: "absent" });
87+
yield* Effect.promise(() => harness.store.save(harness.credentials));
88+
expect(yield* harness.auth.readCredentialState).toEqual({
89+
status: "valid",
90+
apiKey: harness.credentials.apiKey,
91+
backendUrl: harness.credentials.backendUrl,
92+
apiKeyExpiresAtMs: harness.credentials.apiKeyExpiresAtMs,
93+
});
94+
yield* Effect.promise(() =>
95+
harness.store.save({ ...harness.credentials, apiKeyExpiresAtMs: 0 }),
96+
);
97+
expect(yield* harness.auth.readCredentialState).toEqual({ status: "expired" });
98+
expect(yield* harness.auth.readApiKey).toBeUndefined();
99+
}).pipe(Effect.scoped),
100+
);
101+
83102
it.effect("closes SDK sessions and interrupts in-flight credential work before signing out", () =>
84103
Effect.gen(function* () {
85104
const harness = yield* makeHarness();

‎packages/provider-cursor/src/server/auth.ts‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,18 @@ interface AuthFlow {
2727
fiber?: Fiber.Fiber<void>;
2828
}
2929

30+
export type CursorCredentialState =
31+
| { readonly status: "absent" }
32+
| {
33+
readonly status: "valid";
34+
readonly apiKey: string;
35+
readonly backendUrl: string;
36+
readonly apiKeyExpiresAtMs?: number;
37+
}
38+
| { readonly status: "expired" };
39+
3040
export interface CursorAuth {
41+
readonly readCredentialState: Effect.Effect<CursorCredentialState, ProviderSetupError>;
3142
readonly controller: ProviderAuthController;
3243
readonly readApiKey: Effect.Effect<string | undefined, ProviderSetupError>;
3344
readonly requireApiKey: Effect.Effect<string, ProviderSetupError>;
@@ -72,8 +83,7 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu
7283
state: { ...current.state, ...patch },
7384
}));
7485

75-
const readApiKey = Effect.gen(function* () {
76-
if (configuredKey) return configuredKey;
86+
const readCredentialState: CursorAuth["readCredentialState"] = Effect.gen(function* () {
7787
const credentials = yield* Effect.tryPromise({
7888
try: () => options.store.load(),
7989
catch: (cause) =>
@@ -84,12 +94,24 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu
8494
cause,
8595
}),
8696
});
97+
if (!credentials) return { status: "absent" } as const;
8798
const now = yield* Clock.currentTimeMillis;
88-
return credentials &&
89-
(credentials.apiKeyExpiresAtMs === undefined || credentials.apiKeyExpiresAtMs > now)
90-
? credentials.apiKey
91-
: undefined;
99+
if (credentials.apiKeyExpiresAtMs !== undefined && credentials.apiKeyExpiresAtMs <= now)
100+
return { status: "expired" } as const;
101+
return {
102+
status: "valid",
103+
apiKey: credentials.apiKey,
104+
backendUrl: credentials.backendUrl,
105+
...(credentials.apiKeyExpiresAtMs === undefined
106+
? {}
107+
: { apiKeyExpiresAtMs: credentials.apiKeyExpiresAtMs }),
108+
} as const;
92109
});
110+
const readApiKey = configuredKey
111+
? Effect.succeed(configuredKey)
112+
: readCredentialState.pipe(
113+
Effect.map((credential) => (credential.status === "valid" ? credential.apiKey : undefined)),
114+
);
93115

94116
const requireApiKey = Effect.gen(function* () {
95117
if (operation !== "idle") {
@@ -485,6 +507,7 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu
485507

486508
return {
487509
controller,
510+
readCredentialState,
488511
readApiKey,
489512
requireApiKey,
490513
withAccess,

‎packages/provider-cursor/src/server/driver.test.ts‎

Lines changed: 108 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,14 @@ import * as Layer from "effect/Layer";
77
import * as Option from "effect/Option";
88
import * as Stream from "effect/Stream";
99
import { vi } from "vite-plus/test";
10+
import * as HttpClientResponse from "effect/http/HttpClientResponse";
1011
import * as HttpClient from "effect/http/HttpClient";
1112
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
1213

1314
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
1415
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
1516
import { CursorDriver } from "./driver.ts";
17+
import { makeCursorCredentialStore } from "./credentialStore.ts";
1618
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
1719
import * as CursorSdk from "./CursorSdk.ts";
1820
import * as CursorKeychain from "./CursorKeychain.ts";
@@ -91,7 +93,26 @@ it.layer(layerTest)("CursorDriver", (it) => {
9193
};
9294
const openedKeys: Array<string | undefined> = [];
9395
let closed = 0;
96+
const requests: string[] = [];
97+
const usageClient = HttpClient.make((request) => {
98+
requests.push(request.url);
99+
const exchange = request.url.endsWith("/auth/exchange_user_api_key");
100+
expect(request.headers.authorization).toBe(
101+
exchange ? "Bearer instance-browser-key" : "Bearer browser-access-token",
102+
);
103+
return Effect.succeed(
104+
HttpClientResponse.fromWeb(
105+
request,
106+
Response.json(
107+
exchange
108+
? { accessToken: "browser-access-token" }
109+
: { planUsage: { totalPercentUsed: 23 } },
110+
),
111+
),
112+
);
113+
});
94114
const instance = yield* CursorDriver.create(input).pipe(
115+
Effect.provideService(HttpClient.HttpClient, usageClient),
95116
Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
96117
assertComplete: Effect.void,
97118
open: (request) =>
@@ -118,6 +139,7 @@ it.layer(layerTest)("CursorDriver", (it) => {
118139
expect(me).toHaveBeenCalledWith({ apiKey: "instance-browser-key" });
119140
expect(yield* instance.snapshot.getSnapshot).toMatchObject({
120141
status: "ready",
142+
usageLimits: { windows: [{ id: "totalPercentUsed", usedPercent: 23 }] },
121143
auth: {
122144
status: "authenticated",
123145
type: "browser",
@@ -142,7 +164,13 @@ it.layer(layerTest)("CursorDriver", (it) => {
142164
yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
143165
expect(openedKeys).toEqual(["instance-browser-key"]);
144166
expect(closed).toBe(0);
145-
const recreated = yield* CursorDriver.create(input);
167+
expect(requests).toEqual([
168+
"https://api2.cursor.sh/auth/exchange_user_api_key",
169+
"https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage",
170+
]);
171+
const recreated = yield* CursorDriver.create(input).pipe(
172+
Effect.provideService(HttpClient.HttpClient, usageClient),
173+
);
146174
expect((yield* recreated.snapshot.refresh).auth.status).toBe("authenticated");
147175
yield* instance.auth!.logout(Effect.void);
148176
expect(closed).toBe(1);
@@ -157,6 +185,85 @@ it.layer(layerTest)("CursorDriver", (it) => {
157185
}).pipe(Effect.scoped),
158186
);
159187

188+
it.effect("keeps env CURSOR_API_KEY limits unsupported without stored credentials", () =>
189+
Effect.gen(function* () {
190+
const me = vi.spyOn(Cursor, "me").mockResolvedValue({
191+
apiKeyName: "Configured key",
192+
createdAt: "2026-01-01T00:00:00.000Z",
193+
});
194+
const models = vi.spyOn(Cursor.models, "list").mockResolvedValue([]);
195+
yield* Effect.addFinalizer(() =>
196+
Effect.sync(() => {
197+
me.mockRestore();
198+
models.mockRestore();
199+
}),
200+
);
201+
const instance = yield* CursorDriver.create({
202+
instanceId: ProviderInstanceId.make("cursor-configured-key"),
203+
displayName: "Configured Cursor",
204+
enabled: true,
205+
environment: [{ name: "CURSOR_API_KEY", value: "configured-key", sensitive: true }],
206+
config: CursorDriver.defaultConfig(),
207+
}).pipe(
208+
Effect.provideService(
209+
HttpClient.HttpClient,
210+
HttpClient.make(() => Effect.die("must not request usage")),
211+
),
212+
);
213+
expect((yield* instance.snapshot.refresh).usageLimits?.unavailable?.reason).toBe(
214+
"unsupported",
215+
);
216+
}).pipe(Effect.scoped),
217+
);
218+
219+
it.effect("keeps env CURSOR_API_KEY limits unsupported with valid stored credentials", () =>
220+
Effect.gen(function* () {
221+
const me = vi.spyOn(Cursor, "me").mockResolvedValue({
222+
apiKeyName: "Configured key",
223+
createdAt: "2026-01-01T00:00:00.000Z",
224+
});
225+
const models = vi.spyOn(Cursor.models, "list").mockResolvedValue([]);
226+
yield* Effect.addFinalizer(() =>
227+
Effect.sync(() => {
228+
me.mockRestore();
229+
models.mockRestore();
230+
}),
231+
);
232+
const instanceId = ProviderInstanceId.make("cursor-configured-key-with-login");
233+
const { store } = yield* makeCursorCredentialStore(instanceId);
234+
yield* Effect.promise(() =>
235+
store.save({
236+
version: 1,
237+
backendUrl: "https://api2.cursor.sh",
238+
apiKey: "stored-browser-key",
239+
createdAtMs: 0,
240+
apiKeyExpiresAtMs: 4_000_000_000_000,
241+
}),
242+
);
243+
const requests: string[] = [];
244+
const instance = yield* CursorDriver.create({
245+
instanceId,
246+
displayName: "Configured Cursor",
247+
enabled: true,
248+
environment: [{ name: "CURSOR_API_KEY", value: "configured-key", sensitive: true }],
249+
config: CursorDriver.defaultConfig(),
250+
}).pipe(
251+
Effect.provideService(
252+
HttpClient.HttpClient,
253+
HttpClient.make((request) => {
254+
requests.push(request.url);
255+
return Effect.die("must not exchange credentials or request usage");
256+
}),
257+
),
258+
);
259+
expect((yield* instance.snapshot.refresh).usageLimits?.unavailable?.reason).toBe(
260+
"unsupported",
261+
);
262+
expect(requests).toEqual([]);
263+
expect(me).toHaveBeenCalledWith({ apiKey: "configured-key" });
264+
}).pipe(Effect.scoped),
265+
);
266+
160267
it.effect("keeps the bundled SDK manual-only without probing or updating cursor-agent", () =>
161268
Effect.gen(function* () {
162269
const instance = yield* CursorDriver.create({

‎packages/provider-cursor/src/server/driver.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ export const CursorDriver: ProviderDriver<
8787
const host = yield* ProviderHost.ProviderHost;
8888
const fileSystem = yield* FileSystem.FileSystem;
8989
const path = yield* Path.Path;
90+
const crypto = yield* Crypto.Crypto;
9091
const httpClient = yield* HttpClient.HttpClient;
9192
const keychain = yield* CursorKeychain.CursorKeychain;
9293
const sdkRunner = yield* CursorAgentSdk.CursorAgentSdkRunner;
@@ -205,9 +206,20 @@ export const CursorDriver: ProviderDriver<
205206
auth.withAccess,
206207
);
207208

208-
const checkProvider = auth.readApiKey.pipe(
209-
Effect.orElseSucceed(() => undefined),
210-
Effect.flatMap((apiKey) =>
209+
const checkProvider = Effect.gen(function* () {
210+
const credential = auth.usesApiKey
211+
? ({ status: "absent" } as const)
212+
: yield* auth.readCredentialState.pipe(
213+
Effect.orElseSucceed(() => ({ status: "absent" }) as const),
214+
);
215+
const apiKey = auth.usesApiKey
216+
? yield* auth.readApiKey.pipe(Effect.orElseSucceed(() => undefined))
217+
: credential.status === "valid"
218+
? credential.apiKey
219+
: undefined;
220+
return { credential, apiKey };
221+
}).pipe(
222+
Effect.flatMap(({ credential, apiKey }) =>
211223
checkCursorProviderStatus(
212224
effectiveConfig,
213225
{
@@ -219,13 +231,15 @@ export const CursorDriver: ProviderDriver<
219231
Effect.flatMap((snapshot) =>
220232
effectiveConfig.enabled &&
221233
snapshot.installed &&
222-
snapshot.auth.status === "authenticated"
234+
(snapshot.auth.status === "authenticated" ||
235+
(!auth.usesApiKey && credential.status === "expired"))
223236
? host.settings.get.pipe(
224237
Effect.flatMap((settings) =>
225238
readCursorUsageLimits(
226239
effectiveConfig,
227-
{ ...processEnv, CURSOR_API_KEY: apiKey },
240+
auth.usesApiKey ? { ...processEnv, CURSOR_API_KEY: apiKey } : processEnv,
228241
settings.cursorKeychainUsageEnabled,
242+
auth.usesApiKey ? undefined : { instanceId, credential },
229243
),
230244
),
231245
Effect.map((usageLimits) => ({ ...snapshot, usageLimits })),
@@ -234,6 +248,7 @@ export const CursorDriver: ProviderDriver<
234248
),
235249
),
236250
),
251+
Effect.provideService(Crypto.Crypto, crypto),
237252
Effect.provideService(HttpClient.HttpClient, httpClient),
238253
Effect.provideService(FileSystem.FileSystem, fileSystem),
239254
Effect.provideService(Path.Path, path),

0 commit comments

Comments
 (0)