From 265f4dd65b79c363eb529d10a37415f75abc9e5e Mon Sep 17 00:00:00 2001 From: Steliyan Slavov Date: Sun, 18 Oct 2026 17:20:27 +0300 Subject: [PATCH 1/6] 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 --- .../provider-cursor/src/server/auth.test.ts | 19 ++ packages/provider-cursor/src/server/auth.ts | 35 +- .../provider-cursor/src/server/driver.test.ts | 109 ++++++- packages/provider-cursor/src/server/driver.ts | 25 +- .../src/server/usageLimits.test.ts | 300 +++++++++++++++++- .../provider-cursor/src/server/usageLimits.ts | 156 +++++++++ 6 files changed, 631 insertions(+), 13 deletions(-) diff --git a/packages/provider-cursor/src/server/auth.test.ts b/packages/provider-cursor/src/server/auth.test.ts index 3d31211ac5aef..a81d421e7384b 100644 --- a/packages/provider-cursor/src/server/auth.test.ts +++ b/packages/provider-cursor/src/server/auth.test.ts @@ -80,6 +80,25 @@ const phase = (auth: Auth, phase: ProviderAuthState["phase"], session = owner) = ); it.layer(NodeServices.layer)("CursorAuth", (it) => { + it.effect("distinguishes absent, valid and expired stored credentials", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + expect(yield* harness.auth.readCredentialState).toEqual({ status: "absent" }); + yield* Effect.promise(() => harness.store.save(harness.credentials)); + expect(yield* harness.auth.readCredentialState).toEqual({ + status: "valid", + apiKey: harness.credentials.apiKey, + backendUrl: harness.credentials.backendUrl, + apiKeyExpiresAtMs: harness.credentials.apiKeyExpiresAtMs, + }); + yield* Effect.promise(() => + harness.store.save({ ...harness.credentials, apiKeyExpiresAtMs: 0 }), + ); + expect(yield* harness.auth.readCredentialState).toEqual({ status: "expired" }); + expect(yield* harness.auth.readApiKey).toBeUndefined(); + }).pipe(Effect.scoped), + ); + it.effect("closes SDK sessions and interrupts in-flight credential work before signing out", () => Effect.gen(function* () { const harness = yield* makeHarness(); diff --git a/packages/provider-cursor/src/server/auth.ts b/packages/provider-cursor/src/server/auth.ts index 198bbeb37279d..b27cf6ae334c3 100644 --- a/packages/provider-cursor/src/server/auth.ts +++ b/packages/provider-cursor/src/server/auth.ts @@ -27,7 +27,18 @@ interface AuthFlow { fiber?: Fiber.Fiber; } +export type CursorCredentialState = + | { readonly status: "absent" } + | { + readonly status: "valid"; + readonly apiKey: string; + readonly backendUrl: string; + readonly apiKeyExpiresAtMs?: number; + } + | { readonly status: "expired" }; + export interface CursorAuth { + readonly readCredentialState: Effect.Effect; readonly controller: ProviderAuthController; readonly readApiKey: Effect.Effect; readonly requireApiKey: Effect.Effect; @@ -72,8 +83,7 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu state: { ...current.state, ...patch }, })); - const readApiKey = Effect.gen(function* () { - if (configuredKey) return configuredKey; + const readCredentialState: CursorAuth["readCredentialState"] = Effect.gen(function* () { const credentials = yield* Effect.tryPromise({ try: () => options.store.load(), catch: (cause) => @@ -84,12 +94,24 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu cause, }), }); + if (!credentials) return { status: "absent" } as const; const now = yield* Clock.currentTimeMillis; - return credentials && - (credentials.apiKeyExpiresAtMs === undefined || credentials.apiKeyExpiresAtMs > now) - ? credentials.apiKey - : undefined; + if (credentials.apiKeyExpiresAtMs !== undefined && credentials.apiKeyExpiresAtMs <= now) + return { status: "expired" } as const; + return { + status: "valid", + apiKey: credentials.apiKey, + backendUrl: credentials.backendUrl, + ...(credentials.apiKeyExpiresAtMs === undefined + ? {} + : { apiKeyExpiresAtMs: credentials.apiKeyExpiresAtMs }), + } as const; }); + const readApiKey = configuredKey + ? Effect.succeed(configuredKey) + : readCredentialState.pipe( + Effect.map((credential) => (credential.status === "valid" ? credential.apiKey : undefined)), + ); const requireApiKey = Effect.gen(function* () { if (operation !== "idle") { @@ -485,6 +507,7 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu return { controller, + readCredentialState, readApiKey, requireApiKey, withAccess, diff --git a/packages/provider-cursor/src/server/driver.test.ts b/packages/provider-cursor/src/server/driver.test.ts index 8215f6563d488..4e38aaadf5916 100644 --- a/packages/provider-cursor/src/server/driver.test.ts +++ b/packages/provider-cursor/src/server/driver.test.ts @@ -7,12 +7,14 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; import { vi } from "vite-plus/test"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; import * as HttpClient from "effect/http/HttpClient"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import { CursorDriver } from "./driver.ts"; +import { makeCursorCredentialStore } from "./credentialStore.ts"; import * as CursorAgentSdk from "./CursorAgentSdk.ts"; import * as CursorSdk from "./CursorSdk.ts"; import * as CursorKeychain from "./CursorKeychain.ts"; @@ -91,7 +93,26 @@ it.layer(layerTest)("CursorDriver", (it) => { }; const openedKeys: Array = []; let closed = 0; + const requests: string[] = []; + const usageClient = HttpClient.make((request) => { + requests.push(request.url); + const exchange = request.url.endsWith("/auth/exchange_user_api_key"); + expect(request.headers.authorization).toBe( + exchange ? "Bearer instance-browser-key" : "Bearer browser-access-token", + ); + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json( + exchange + ? { accessToken: "browser-access-token" } + : { planUsage: { totalPercentUsed: 23 } }, + ), + ), + ); + }); const instance = yield* CursorDriver.create(input).pipe( + Effect.provideService(HttpClient.HttpClient, usageClient), Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { assertComplete: Effect.void, open: (request) => @@ -118,6 +139,7 @@ it.layer(layerTest)("CursorDriver", (it) => { expect(me).toHaveBeenCalledWith({ apiKey: "instance-browser-key" }); expect(yield* instance.snapshot.getSnapshot).toMatchObject({ status: "ready", + usageLimits: { windows: [{ id: "totalPercentUsed", usedPercent: 23 }] }, auth: { status: "authenticated", type: "browser", @@ -142,7 +164,13 @@ it.layer(layerTest)("CursorDriver", (it) => { yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy }); expect(openedKeys).toEqual(["instance-browser-key"]); expect(closed).toBe(0); - const recreated = yield* CursorDriver.create(input); + expect(requests).toEqual([ + "https://api2.cursor.sh/auth/exchange_user_api_key", + "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage", + ]); + const recreated = yield* CursorDriver.create(input).pipe( + Effect.provideService(HttpClient.HttpClient, usageClient), + ); expect((yield* recreated.snapshot.refresh).auth.status).toBe("authenticated"); yield* instance.auth!.logout(Effect.void); expect(closed).toBe(1); @@ -157,6 +185,85 @@ it.layer(layerTest)("CursorDriver", (it) => { }).pipe(Effect.scoped), ); + it.effect("keeps env CURSOR_API_KEY limits unsupported without stored credentials", () => + Effect.gen(function* () { + const me = vi.spyOn(Cursor, "me").mockResolvedValue({ + apiKeyName: "Configured key", + createdAt: "2026-01-01T00:00:00.000Z", + }); + const models = vi.spyOn(Cursor.models, "list").mockResolvedValue([]); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + me.mockRestore(); + models.mockRestore(); + }), + ); + const instance = yield* CursorDriver.create({ + instanceId: ProviderInstanceId.make("cursor-configured-key"), + displayName: "Configured Cursor", + enabled: true, + environment: [{ name: "CURSOR_API_KEY", value: "configured-key", sensitive: true }], + config: CursorDriver.defaultConfig(), + }).pipe( + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("must not request usage")), + ), + ); + expect((yield* instance.snapshot.refresh).usageLimits?.unavailable?.reason).toBe( + "unsupported", + ); + }).pipe(Effect.scoped), + ); + + it.effect("keeps env CURSOR_API_KEY limits unsupported with valid stored credentials", () => + Effect.gen(function* () { + const me = vi.spyOn(Cursor, "me").mockResolvedValue({ + apiKeyName: "Configured key", + createdAt: "2026-01-01T00:00:00.000Z", + }); + const models = vi.spyOn(Cursor.models, "list").mockResolvedValue([]); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + me.mockRestore(); + models.mockRestore(); + }), + ); + const instanceId = ProviderInstanceId.make("cursor-configured-key-with-login"); + const { store } = yield* makeCursorCredentialStore(instanceId); + yield* Effect.promise(() => + store.save({ + version: 1, + backendUrl: "https://api2.cursor.sh", + apiKey: "stored-browser-key", + createdAtMs: 0, + apiKeyExpiresAtMs: 4_000_000_000_000, + }), + ); + const requests: string[] = []; + const instance = yield* CursorDriver.create({ + instanceId, + displayName: "Configured Cursor", + enabled: true, + environment: [{ name: "CURSOR_API_KEY", value: "configured-key", sensitive: true }], + config: CursorDriver.defaultConfig(), + }).pipe( + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => { + requests.push(request.url); + return Effect.die("must not exchange credentials or request usage"); + }), + ), + ); + expect((yield* instance.snapshot.refresh).usageLimits?.unavailable?.reason).toBe( + "unsupported", + ); + expect(requests).toEqual([]); + expect(me).toHaveBeenCalledWith({ apiKey: "configured-key" }); + }).pipe(Effect.scoped), + ); + it.effect("keeps the bundled SDK manual-only without probing or updating cursor-agent", () => Effect.gen(function* () { const instance = yield* CursorDriver.create({ diff --git a/packages/provider-cursor/src/server/driver.ts b/packages/provider-cursor/src/server/driver.ts index e938024ffc58a..30e0268a40cfb 100644 --- a/packages/provider-cursor/src/server/driver.ts +++ b/packages/provider-cursor/src/server/driver.ts @@ -87,6 +87,7 @@ export const CursorDriver: ProviderDriver< const host = yield* ProviderHost.ProviderHost; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const crypto = yield* Crypto.Crypto; const httpClient = yield* HttpClient.HttpClient; const keychain = yield* CursorKeychain.CursorKeychain; const sdkRunner = yield* CursorAgentSdk.CursorAgentSdkRunner; @@ -205,9 +206,20 @@ export const CursorDriver: ProviderDriver< auth.withAccess, ); - const checkProvider = auth.readApiKey.pipe( - Effect.orElseSucceed(() => undefined), - Effect.flatMap((apiKey) => + const checkProvider = Effect.gen(function* () { + const credential = auth.usesApiKey + ? ({ status: "absent" } as const) + : yield* auth.readCredentialState.pipe( + Effect.orElseSucceed(() => ({ status: "absent" }) as const), + ); + const apiKey = auth.usesApiKey + ? yield* auth.readApiKey.pipe(Effect.orElseSucceed(() => undefined)) + : credential.status === "valid" + ? credential.apiKey + : undefined; + return { credential, apiKey }; + }).pipe( + Effect.flatMap(({ credential, apiKey }) => checkCursorProviderStatus( effectiveConfig, { @@ -219,13 +231,15 @@ export const CursorDriver: ProviderDriver< Effect.flatMap((snapshot) => effectiveConfig.enabled && snapshot.installed && - snapshot.auth.status === "authenticated" + (snapshot.auth.status === "authenticated" || + (!auth.usesApiKey && credential.status === "expired")) ? host.settings.get.pipe( Effect.flatMap((settings) => readCursorUsageLimits( effectiveConfig, - { ...processEnv, CURSOR_API_KEY: apiKey }, + auth.usesApiKey ? { ...processEnv, CURSOR_API_KEY: apiKey } : processEnv, settings.cursorKeychainUsageEnabled, + auth.usesApiKey ? undefined : { instanceId, credential }, ), ), Effect.map((usageLimits) => ({ ...snapshot, usageLimits })), @@ -234,6 +248,7 @@ export const CursorDriver: ProviderDriver< ), ), ), + Effect.provideService(Crypto.Crypto, crypto), Effect.provideService(HttpClient.HttpClient, httpClient), Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), diff --git a/packages/provider-cursor/src/server/usageLimits.test.ts b/packages/provider-cursor/src/server/usageLimits.test.ts index ce8a2cbc27cf3..e281a74c78199 100644 --- a/packages/provider-cursor/src/server/usageLimits.test.ts +++ b/packages/provider-cursor/src/server/usageLimits.test.ts @@ -1,6 +1,13 @@ import { describe, expect, it } from "@effect/vitest"; import { NodeServices } from "@effect/platform-node"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as TestClock from "effect/testing/TestClock"; +import * as Crypto from "effect/Crypto"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import type * as HttpClientRequest from "effect/http/HttpClientRequest"; +import type { CursorCredentialState } from "./auth.ts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -10,7 +17,11 @@ import * as CursorKeychain from "./CursorKeychain.ts"; import { cursorUsageResponseToLimits, readCursorUsageLimits } from "./usageLimits.ts"; const withNodeServices = ( - effect: Effect.Effect, + effect: Effect.Effect< + A, + E, + FileSystem.FileSystem | Path.Path | Crypto.Crypto | CursorKeychain.CursorKeychain + >, accessToken: CursorKeychain.CursorKeychain["Service"]["accessToken"] = Effect.die( "must not read Keychain", ), @@ -271,3 +282,290 @@ describe("Cursor usage limits", () => { }), ); }); + +const exchangePath = "/auth/exchange_user_api_key"; +const usagePath = "/aiserver.v1.DashboardService/GetCurrentPeriodUsage"; +const storedCredential = { + status: "valid", + apiKey: "private-instance-key", + backendUrl: "https://instance.example/path", +} as const; +const usage = () => Response.json({ planUsage: { totalPercentUsed: 37 } }); +const makeProbe = ( + instanceId: string, + answer: (request: HttpClientRequest.HttpClientRequest, index: number) => Response = (request) => + request.url.endsWith(exchangePath) + ? Response.json({ accessToken: "private-access-token" }) + : usage(), +) => { + const requests: HttpClientRequest.HttpClientRequest[] = []; + const client = HttpClient.make((request, _url, _signal, fiber) => { + expect(Context.getOrUndefined(fiber.context, FetchHttpClient.RequestInit)?.redirect).toBe( + "error", + ); + expect(request.method).toBe("POST"); + expect(request.headers["content-type"]).toBe("application/json"); + expect( + request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : null, + ).toBe("{}"); + requests.push(request); + return Effect.succeed( + HttpClientResponse.fromWeb(request, answer(request, requests.length - 1)), + ); + }); + const probe = ( + credential: CursorCredentialState = storedCredential, + environment: NodeJS.ProcessEnv = {}, + ) => + withNodeServices( + readCursorUsageLimits({ apiEndpoint: "https://unrelated.example" }, environment, true, { + instanceId, + credential, + }).pipe( + Effect.provideService(HttpClient.HttpClient, client), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService( + FileSystem.FileSystem, + FileSystem.makeNoop({ + readFileString: () => Effect.die("must not read host auth"), + }), + ), + ), + ); + return { probe, requests }; +}; + +it.effect( + "publishes stored-login limits at its backend origin without reading host credentials", + () => + Effect.gen(function* () { + for (const [index, environment] of [ + {}, + { CURSOR_AUTH_TOKEN: "other-host-account" }, + { AGENT_CLI_CREDENTIAL_STORE: "file" }, + { AGENT_CLI_CREDENTIAL_STORE: "default" }, + ].entries()) { + const harness = makeProbe(`own-login-${index}`); + expect((yield* harness.probe(storedCredential, environment)).windows[0]?.usedPercent).toBe( + 37, + ); + expect( + harness.requests.map((request) => [request.url, request.headers.authorization]), + ).toEqual([ + [`https://instance.example${exchangePath}`, "Bearer private-instance-key"], + [`https://instance.example${usagePath}`, "Bearer private-access-token"], + ]); + expect(harness.requests[1]?.headers["x-cursor-client-type"]).toBe("sdk"); + expect(harness.requests[1]?.headers["connect-protocol-version"]).toBe("1"); + } + }), +); + +it.effect("reports expired credentials as requiring re-login without requests", () => + Effect.gen(function* () { + const harness = makeProbe("expired"); + expect((yield* harness.probe({ status: "expired" })).unavailable).toMatchObject({ + reason: "unsupported", + message: expect.stringContaining("Sign in again"), + }); + expect(harness.requests).toHaveLength(0); + }), +); + +it.effect("reuses a cached token on the next probe", () => + Effect.gen(function* () { + const harness = makeProbe("cache-reuse"); + yield* harness.probe(); + expect((yield* harness.probe()).windows[0]?.usedPercent).toBe(37); + expect(harness.requests.map((request) => request.url)).toEqual([ + `https://instance.example${exchangePath}`, + `https://instance.example${usagePath}`, + `https://instance.example${usagePath}`, + ]); + }), +); + +it.effect("exchanges a new token when the same instance and key change backend origin", () => + Effect.gen(function* () { + const harness = makeProbe("cache-origin-change", (request) => + request.url.endsWith(exchangePath) + ? Response.json({ + accessToken: request.url.startsWith("https://instance.example/") + ? "old-origin-token" + : "new-origin-token", + }) + : usage(), + ); + yield* harness.probe(); + expect( + (yield* harness.probe({ ...storedCredential, backendUrl: "https://new.example/path" })) + .windows[0]?.usedPercent, + ).toBe(37); + expect(harness.requests.map((request) => [request.url, request.headers.authorization])).toEqual( + [ + [`https://instance.example${exchangePath}`, "Bearer private-instance-key"], + [`https://instance.example${usagePath}`, "Bearer old-origin-token"], + [`https://new.example${exchangePath}`, "Bearer private-instance-key"], + [`https://new.example${usagePath}`, "Bearer new-origin-token"], + ], + ); + yield* harness.probe(); + expect(harness.requests.slice(4).map((request) => request.url)).toEqual([ + `https://instance.example${exchangePath}`, + `https://instance.example${usagePath}`, + ]); + }), +); + +it.effect("refreshes a JWT at its seconds-based expiry minus the 60-second margin", () => + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + const exp = Math.floor(now / 1000) + 600; + const jwt = [ + Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString("base64url"), + Buffer.from(JSON.stringify({ exp })).toString("base64url"), + Buffer.from("test-signature").toString("base64url"), + ].join("."); + const harness = makeProbe("jwt-expiry", (request, index) => + request.url.endsWith(exchangePath) + ? Response.json({ accessToken: index === 0 ? jwt : "refreshed-token" }) + : usage(), + ); + yield* harness.probe(); + yield* TestClock.adjust(exp * 1000 - 60_000 - now - 1); + expect((yield* harness.probe()).windows[0]?.usedPercent).toBe(37); + expect(harness.requests.map((request) => request.headers.authorization)).toEqual([ + "Bearer private-instance-key", + `Bearer ${jwt}`, + `Bearer ${jwt}`, + ]); + yield* TestClock.adjust(2); + expect((yield* harness.probe()).windows[0]?.usedPercent).toBe(37); + expect( + harness.requests.slice(3).map((request) => [request.url, request.headers.authorization]), + ).toEqual([ + [`https://instance.example${exchangePath}`, "Bearer private-instance-key"], + [`https://instance.example${usagePath}`, "Bearer refreshed-token"], + ]); + }), +); + +it.effect("re-exchanges a cached-token 401 once and reports a second 401 as probeFailed", () => + Effect.gen(function* () { + for (const retryStatus of [200, 401]) { + const harness = makeProbe(`cached-401-${retryStatus}`, (request, index) => + request.url.endsWith(exchangePath) + ? Response.json({ accessToken: `access-${index}` }) + : index === 2 || (index === 4 && retryStatus === 401) + ? new Response("private-response", { status: 401 }) + : usage(), + ); + yield* harness.probe(); + const result = yield* harness.probe(); + expect(harness.requests.map((request) => request.url.split("/").at(-1))).toEqual([ + "exchange_user_api_key", + "GetCurrentPeriodUsage", + "GetCurrentPeriodUsage", + "exchange_user_api_key", + "GetCurrentPeriodUsage", + ]); + expect(harness.requests[4]?.headers.authorization).toBe("Bearer access-3"); + if (retryStatus === 200) expect(result.windows[0]?.usedPercent).toBe(37); + else expect(result.unavailable?.reason).toBe("probeFailed"); + } + }), +); + +it.effect("handles exchange rejection, rate limits and redirects without retries", () => + Effect.gen(function* () { + for (const [status, reason] of [ + [401, "unsupported"], + [429, "probeFailed"], + [302, "probeFailed"], + ] as const) { + const harness = makeProbe( + `exchange-${status}`, + () => + new Response("private-response", { + status, + headers: { location: "https://redirect.example" }, + }), + ); + const result = yield* harness.probe(); + expect(result.unavailable?.reason).toBe(reason); + expect(harness.requests).toHaveLength(1); + expect(JSON.stringify(result)).not.toContain("private-response"); + } + }), +); + +it.effect("refuses insecure and userinfo backends with zero requests", () => + Effect.gen(function* () { + const harness = makeProbe("invalid-backends"); + for (const backendUrl of [ + "http://instance.example", + "https://user@instance.example", + "https://user:password@instance.example", + ]) { + expect((yield* harness.probe({ ...storedCredential, backendUrl })).unavailable?.reason).toBe( + "probeFailed", + ); + } + expect(harness.requests).toHaveLength(0); + }), +); + +it.effect("isolates instance caches and prunes the old key on rotation", () => + Effect.gen(function* () { + const first = makeProbe("cache-first"); + const second = makeProbe("cache-second"); + yield* first.probe(); + yield* second.probe(); + yield* first.probe(); + yield* second.probe(); + expect(first.requests).toHaveLength(3); + expect(second.requests).toHaveLength(3); + yield* first.probe({ ...storedCredential, apiKey: "rotated-key" }); + yield* first.probe(); + expect(first.requests.slice(3).map((request) => request.url)).toEqual([ + `https://instance.example${exchangePath}`, + `https://instance.example${usagePath}`, + `https://instance.example${exchangePath}`, + `https://instance.example${usagePath}`, + ]); + yield* second.probe(); + expect(second.requests).toHaveLength(4); + }), +); + +it.effect("keeps secrets out of usage failure strings", () => + Effect.gen(function* () { + const harness = makeProbe("secret-output", (request) => + request.url.endsWith(exchangePath) + ? Response.json({ + accessToken: "private-access-token", + refreshToken: "private-refresh-token", + }) + : new Response("private-response-body", { status: 500 }), + ); + const result = yield* harness.probe(); + expect(harness.requests.map((request) => [request.url, request.headers.authorization])).toEqual( + [ + [`https://instance.example${exchangePath}`, "Bearer private-instance-key"], + [`https://instance.example${usagePath}`, "Bearer private-access-token"], + ], + ); + expect(result.unavailable).toEqual({ + reason: "probeFailed", + message: "Cursor could not read usage limits.", + }); + const output = JSON.stringify(result); + for (const secret of [ + "private-instance-key", + "private-access-token", + "private-refresh-token", + "private-response-body", + ]) + expect(output).not.toContain(secret); + }), +); diff --git a/packages/provider-cursor/src/server/usageLimits.ts b/packages/provider-cursor/src/server/usageLimits.ts index 049e646d2c492..1761df1fc8346 100644 --- a/packages/provider-cursor/src/server/usageLimits.ts +++ b/packages/provider-cursor/src/server/usageLimits.ts @@ -2,12 +2,19 @@ import type { ServerProviderUsageWindow } from "@t3tools/contracts"; import type { CursorSettings } from "../settings.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { CURSOR_USAGE_WINDOWS } from "@t3tools/shared/usageLimits"; +import * as Clock from "effect/Clock"; +import * as Crypto from "effect/Crypto"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as Hex from "effect/encoding/Hex"; +import * as Result from "effect/Result"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import type { CursorCredentialState } from "./auth.ts"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientRequest from "effect/http/HttpClientRequest"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; @@ -61,13 +68,162 @@ export function cursorUsageResponseToLimits( : makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); } +interface UsageToken { + readonly accessToken: string; + readonly expiresAtMs: number; +} +const tokens = new Map(); +const exchanges = new Map< + string, + Effect.Effect< + UsageToken | undefined, + Effect.Error>, + HttpClient.HttpClient + > +>(); + +export function pruneCursorUsageTokens(instanceId: string, keepKey?: string): void { + for (const entries of [tokens, exchanges]) { + for (const existing of entries.keys()) { + if (existing.startsWith(`${instanceId.length}:${instanceId}:`) && existing !== keepKey) + entries.delete(existing); + } + } +} + +const decodeTokenClaims = Schema.decodeOption( + Schema.fromJsonString(Schema.Struct({ exp: Schema.Number })), +); + +function tokenExpiresAt(accessToken: string, now: number): number { + const parts = accessToken.split("."); + if (parts.length !== 3) return now + 300_000; + const decoded = Base64Url.decodeString(parts[1]!); + if (Result.isFailure(decoded)) return now + 300_000; + // JWT claims only bound the cache lifetime; the backend validates the bearer. + const claims = decodeTokenClaims(decoded.success); + if (Option.isSome(claims)) { + const expiresAtMs = claims.value.exp * 1000 - 60_000; + if (Number.isFinite(expiresAtMs)) return expiresAtMs; + } + return now + 300_000; +} + +const exchangeToken = (endpoint: string, apiKey: string) => + Effect.gen(function* () { + const client = yield* HttpClient.HttpClient; + const response = yield* client.execute( + HttpClientRequest.post(`${endpoint}/auth/exchange_user_api_key`).pipe( + HttpClientRequest.bearerToken(apiKey), + HttpClientRequest.bodyJsonUnsafe({}), + ), + ); + if (response.status === 401) return undefined; + const body = yield* HttpClientResponse.schemaBodyJson( + Schema.Struct({ accessToken: Schema.NonEmptyString }), + )(yield* HttpClientResponse.filterStatusOk(response)); + return { + accessToken: body.accessToken, + expiresAtMs: tokenExpiresAt(body.accessToken, yield* Clock.currentTimeMillis), + }; + }); + +const getInstanceToken = (key: string, endpoint: string, apiKey: string) => + Effect.gen(function* () { + const pending = exchanges.get(key); + if (pending) return yield* pending; + const operation = yield* Effect.cached( + exchangeToken(endpoint, apiKey).pipe( + Effect.tap((token) => + Effect.sync(() => { + // A rotated or logged-out instance must not be repopulated by an older exchange. + if (token && exchanges.get(key) === operation) tokens.set(key, token); + }), + ), + Effect.ensuring( + Effect.sync(() => { + if (exchanges.get(key) === operation) exchanges.delete(key); + }), + ), + ), + ); + exchanges.set(key, operation); + return yield* operation; + }); + +const readInstanceUsage = ( + instanceId: string, + credential: CursorCredentialState, + checkedAt: string, +) => + Effect.gen(function* () { + if (credential.status !== "valid") pruneCursorUsageTokens(instanceId); + const authRequired = () => + makeUnavailableUsageLimits({ + checkedAt, + reason: "unsupported", + message: "Cursor sign-in expired or was rejected. Sign in again in provider settings.", + }); + if (credential.status === "absent") return undefined; + if (credential.status === "expired") return authRequired(); + const endpoint = yield* Effect.try(() => { + const url = new URL(credential.backendUrl); + if (url.protocol !== "https:" || url.username || url.password) + throw new Error("Invalid Cursor credential backend."); + return url.origin; + }); + const crypto = yield* Crypto.Crypto; + const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(credential.apiKey)); + const key = `${instanceId.length}:${instanceId}:${endpoint}:${Hex.encode(digest)}`; + pruneCursorUsageTokens(instanceId, key); + const now = yield* Clock.currentTimeMillis; + const cached = tokens.get(key); + const usable = cached && cached.expiresAtMs > now ? cached : undefined; + if (!usable) tokens.delete(key); + let token = usable ?? (yield* getInstanceToken(key, endpoint, credential.apiKey)); + if (!token) return authRequired(); + const client = yield* HttpClient.HttpClient; + const requestUsage = (accessToken: string) => + client.execute( + HttpClientRequest.post( + `${endpoint}/aiserver.v1.DashboardService/GetCurrentPeriodUsage`, + ).pipe( + HttpClientRequest.bearerToken(accessToken), + HttpClientRequest.setHeaders({ + "connect-protocol-version": "1", + "x-cursor-client-type": "sdk", + }), + HttpClientRequest.bodyJsonUnsafe({}), + ), + ); + let response = yield* requestUsage(token.accessToken); + if (response.status === 401) { + if (tokens.get(key) === token) tokens.delete(key); + if (usable) { + token = yield* getInstanceToken(key, endpoint, credential.apiKey); + if (!token) return authRequired(); + response = yield* requestUsage(token.accessToken); + if (response.status === 401 && tokens.get(key) === token) tokens.delete(key); + } + } + const body = yield* HttpClientResponse.schemaBodyJson(CursorUsageResponse)( + yield* HttpClientResponse.filterStatusOk(response), + ); + return cursorUsageResponseToLimits(body, checkedAt); + }).pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" })); + export const readCursorUsageLimits = Effect.fn("readCursorUsageLimits")(function* ( settings: Pick, environment: NodeJS.ProcessEnv = process.env, allowKeychain = false, + instance?: { readonly instanceId: string; readonly credential: CursorCredentialState }, ) { const checkedAt = DateTime.formatIso(yield* DateTime.now); return yield* Effect.gen(function* () { + if (instance) { + const limits = yield* readInstanceUsage(instance.instanceId, instance.credential, checkedAt); + if (limits) return limits; + } const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const platform = yield* HostProcess.Platform; From c4fde6641e8d41ee7fa9b6ee3e5714bc6251ef3c Mon Sep 17 00:00:00 2001 From: Steliyan Slavov Date: Sun, 18 Oct 2026 18:37:19 +0300 Subject: [PATCH 2/6] refactor(cursor): keep usage token pruning private Co-Authored-By: Claude Opus 5.5 --- packages/provider-cursor/src/server/usageLimits.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/provider-cursor/src/server/usageLimits.ts b/packages/provider-cursor/src/server/usageLimits.ts index 1761df1fc8346..21d6159d7af14 100644 --- a/packages/provider-cursor/src/server/usageLimits.ts +++ b/packages/provider-cursor/src/server/usageLimits.ts @@ -82,7 +82,7 @@ const exchanges = new Map< > >(); -export function pruneCursorUsageTokens(instanceId: string, keepKey?: string): void { +function pruneCursorUsageTokens(instanceId: string, keepKey?: string): void { for (const entries of [tokens, exchanges]) { for (const existing of entries.keys()) { if (existing.startsWith(`${instanceId.length}:${instanceId}:`) && existing !== keepKey) From d61bee9aae8138ea2923008d644dc8e6c2f4ed24 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 02:15:27 +0000 Subject: [PATCH 3/6] fix(cursor): simplify browser login usage limits --- .../provider-cursor/src/server/auth.test.ts | 19 - packages/provider-cursor/src/server/auth.ts | 28 +- .../provider-cursor/src/server/driver.test.ts | 125 +++--- packages/provider-cursor/src/server/driver.ts | 26 +- .../src/server/usageLimits.test.ts | 380 ++++-------------- .../provider-cursor/src/server/usageLimits.ts | 200 +++------ 6 files changed, 205 insertions(+), 573 deletions(-) diff --git a/packages/provider-cursor/src/server/auth.test.ts b/packages/provider-cursor/src/server/auth.test.ts index a81d421e7384b..3d31211ac5aef 100644 --- a/packages/provider-cursor/src/server/auth.test.ts +++ b/packages/provider-cursor/src/server/auth.test.ts @@ -80,25 +80,6 @@ const phase = (auth: Auth, phase: ProviderAuthState["phase"], session = owner) = ); it.layer(NodeServices.layer)("CursorAuth", (it) => { - it.effect("distinguishes absent, valid and expired stored credentials", () => - Effect.gen(function* () { - const harness = yield* makeHarness(); - expect(yield* harness.auth.readCredentialState).toEqual({ status: "absent" }); - yield* Effect.promise(() => harness.store.save(harness.credentials)); - expect(yield* harness.auth.readCredentialState).toEqual({ - status: "valid", - apiKey: harness.credentials.apiKey, - backendUrl: harness.credentials.backendUrl, - apiKeyExpiresAtMs: harness.credentials.apiKeyExpiresAtMs, - }); - yield* Effect.promise(() => - harness.store.save({ ...harness.credentials, apiKeyExpiresAtMs: 0 }), - ); - expect(yield* harness.auth.readCredentialState).toEqual({ status: "expired" }); - expect(yield* harness.auth.readApiKey).toBeUndefined(); - }).pipe(Effect.scoped), - ); - it.effect("closes SDK sessions and interrupts in-flight credential work before signing out", () => Effect.gen(function* () { const harness = yield* makeHarness(); diff --git a/packages/provider-cursor/src/server/auth.ts b/packages/provider-cursor/src/server/auth.ts index b27cf6ae334c3..d4fdd01283a80 100644 --- a/packages/provider-cursor/src/server/auth.ts +++ b/packages/provider-cursor/src/server/auth.ts @@ -27,20 +27,19 @@ interface AuthFlow { fiber?: Fiber.Fiber; } -export type CursorCredentialState = - | { readonly status: "absent" } +/** A Cursor login saved by T3's browser sign-in, as opposed to a configured API key. */ +export type CursorStoredLogin = | { readonly status: "valid"; readonly apiKey: string; readonly backendUrl: string; - readonly apiKeyExpiresAtMs?: number; } | { readonly status: "expired" }; export interface CursorAuth { - readonly readCredentialState: Effect.Effect; readonly controller: ProviderAuthController; readonly readApiKey: Effect.Effect; + readonly readStoredLogin: Effect.Effect; readonly requireApiKey: Effect.Effect; readonly usesApiKey: boolean; readonly withAccess: ( @@ -83,7 +82,7 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu state: { ...current.state, ...patch }, })); - const readCredentialState: CursorAuth["readCredentialState"] = Effect.gen(function* () { + const readStoredLogin: CursorAuth["readStoredLogin"] = Effect.gen(function* () { const credentials = yield* Effect.tryPromise({ try: () => options.store.load(), catch: (cause) => @@ -94,23 +93,22 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu cause, }), }); - if (!credentials) return { status: "absent" } as const; + if (!credentials) return undefined; const now = yield* Clock.currentTimeMillis; - if (credentials.apiKeyExpiresAtMs !== undefined && credentials.apiKeyExpiresAtMs <= now) - return { status: "expired" } as const; + if (credentials.apiKeyExpiresAtMs !== undefined && credentials.apiKeyExpiresAtMs <= now) { + return { status: "expired" }; + } return { status: "valid", apiKey: credentials.apiKey, backendUrl: credentials.backendUrl, - ...(credentials.apiKeyExpiresAtMs === undefined - ? {} - : { apiKeyExpiresAtMs: credentials.apiKeyExpiresAtMs }), - } as const; + }; }); + const readApiKey = configuredKey ? Effect.succeed(configuredKey) - : readCredentialState.pipe( - Effect.map((credential) => (credential.status === "valid" ? credential.apiKey : undefined)), + : readStoredLogin.pipe( + Effect.map((login) => (login?.status === "valid" ? login.apiKey : undefined)), ); const requireApiKey = Effect.gen(function* () { @@ -507,8 +505,8 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu return { controller, - readCredentialState, readApiKey, + readStoredLogin, requireApiKey, withAccess, usesApiKey: configuredKey !== undefined, diff --git a/packages/provider-cursor/src/server/driver.test.ts b/packages/provider-cursor/src/server/driver.test.ts index 4e38aaadf5916..4873f74a13501 100644 --- a/packages/provider-cursor/src/server/driver.test.ts +++ b/packages/provider-cursor/src/server/driver.test.ts @@ -164,7 +164,7 @@ it.layer(layerTest)("CursorDriver", (it) => { yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy }); expect(openedKeys).toEqual(["instance-browser-key"]); expect(closed).toBe(0); - expect(requests).toEqual([ + expect(requests.slice(0, 2)).toEqual([ "https://api2.cursor.sh/auth/exchange_user_api_key", "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage", ]); @@ -185,83 +185,54 @@ it.layer(layerTest)("CursorDriver", (it) => { }).pipe(Effect.scoped), ); - it.effect("keeps env CURSOR_API_KEY limits unsupported without stored credentials", () => - Effect.gen(function* () { - const me = vi.spyOn(Cursor, "me").mockResolvedValue({ - apiKeyName: "Configured key", - createdAt: "2026-01-01T00:00:00.000Z", - }); - const models = vi.spyOn(Cursor.models, "list").mockResolvedValue([]); - yield* Effect.addFinalizer(() => - Effect.sync(() => { - me.mockRestore(); - models.mockRestore(); - }), - ); - const instance = yield* CursorDriver.create({ - instanceId: ProviderInstanceId.make("cursor-configured-key"), - displayName: "Configured Cursor", - enabled: true, - environment: [{ name: "CURSOR_API_KEY", value: "configured-key", sensitive: true }], - config: CursorDriver.defaultConfig(), - }).pipe( - Effect.provideService( - HttpClient.HttpClient, - HttpClient.make(() => Effect.die("must not request usage")), - ), - ); - expect((yield* instance.snapshot.refresh).usageLimits?.unavailable?.reason).toBe( - "unsupported", - ); - }).pipe(Effect.scoped), - ); - - it.effect("keeps env CURSOR_API_KEY limits unsupported with valid stored credentials", () => - Effect.gen(function* () { - const me = vi.spyOn(Cursor, "me").mockResolvedValue({ - apiKeyName: "Configured key", - createdAt: "2026-01-01T00:00:00.000Z", - }); - const models = vi.spyOn(Cursor.models, "list").mockResolvedValue([]); - yield* Effect.addFinalizer(() => - Effect.sync(() => { - me.mockRestore(); - models.mockRestore(); - }), - ); - const instanceId = ProviderInstanceId.make("cursor-configured-key-with-login"); - const { store } = yield* makeCursorCredentialStore(instanceId); - yield* Effect.promise(() => - store.save({ - version: 1, - backendUrl: "https://api2.cursor.sh", - apiKey: "stored-browser-key", - createdAtMs: 0, - apiKeyExpiresAtMs: 4_000_000_000_000, - }), - ); - const requests: string[] = []; - const instance = yield* CursorDriver.create({ - instanceId, - displayName: "Configured Cursor", - enabled: true, - environment: [{ name: "CURSOR_API_KEY", value: "configured-key", sensitive: true }], - config: CursorDriver.defaultConfig(), - }).pipe( - Effect.provideService( - HttpClient.HttpClient, - HttpClient.make((request) => { - requests.push(request.url); - return Effect.die("must not exchange credentials or request usage"); + it.effect( + "keeps a configured CURSOR_API_KEY instance off its stored browser login for limits", + () => + Effect.gen(function* () { + const me = vi.spyOn(Cursor, "me").mockResolvedValue({ + apiKeyName: "Configured key", + createdAt: "2026-01-01T00:00:00.000Z", + }); + const models = vi.spyOn(Cursor.models, "list").mockResolvedValue([]); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + me.mockRestore(); + models.mockRestore(); + }), + ); + const instanceId = ProviderInstanceId.make("cursor-configured-key-with-login"); + const { store } = yield* makeCursorCredentialStore(instanceId); + yield* Effect.promise(() => + store.save({ + version: 1, + backendUrl: "https://api2.cursor.sh", + apiKey: "stored-browser-key", + createdAtMs: 0, + apiKeyExpiresAtMs: 4_000_000_000_000, }), - ), - ); - expect((yield* instance.snapshot.refresh).usageLimits?.unavailable?.reason).toBe( - "unsupported", - ); - expect(requests).toEqual([]); - expect(me).toHaveBeenCalledWith({ apiKey: "configured-key" }); - }).pipe(Effect.scoped), + ); + const requests: string[] = []; + const instance = yield* CursorDriver.create({ + instanceId, + displayName: "Configured Cursor", + enabled: true, + environment: [{ name: "CURSOR_API_KEY", value: "configured-key", sensitive: true }], + config: CursorDriver.defaultConfig(), + }).pipe( + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => { + requests.push(request.url); + return Effect.die("must not exchange credentials or request usage"); + }), + ), + ); + expect((yield* instance.snapshot.refresh).usageLimits?.unavailable?.reason).toBe( + "unsupported", + ); + expect(requests).toEqual([]); + expect(me).toHaveBeenCalledWith({ apiKey: "configured-key" }); + }).pipe(Effect.scoped), ); it.effect("keeps the bundled SDK manual-only without probing or updating cursor-agent", () => diff --git a/packages/provider-cursor/src/server/driver.ts b/packages/provider-cursor/src/server/driver.ts index 30e0268a40cfb..34f675f4c9500 100644 --- a/packages/provider-cursor/src/server/driver.ts +++ b/packages/provider-cursor/src/server/driver.ts @@ -87,7 +87,6 @@ export const CursorDriver: ProviderDriver< const host = yield* ProviderHost.ProviderHost; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const crypto = yield* Crypto.Crypto; const httpClient = yield* HttpClient.HttpClient; const keychain = yield* CursorKeychain.CursorKeychain; const sdkRunner = yield* CursorAgentSdk.CursorAgentSdkRunner; @@ -207,19 +206,17 @@ export const CursorDriver: ProviderDriver< ); const checkProvider = Effect.gen(function* () { - const credential = auth.usesApiKey - ? ({ status: "absent" } as const) - : yield* auth.readCredentialState.pipe( - Effect.orElseSucceed(() => ({ status: "absent" }) as const), - ); + const storedLogin = auth.usesApiKey + ? undefined + : yield* auth.readStoredLogin.pipe(Effect.orElseSucceed(() => undefined)); const apiKey = auth.usesApiKey ? yield* auth.readApiKey.pipe(Effect.orElseSucceed(() => undefined)) - : credential.status === "valid" - ? credential.apiKey + : storedLogin?.status === "valid" + ? storedLogin.apiKey : undefined; - return { credential, apiKey }; + return { storedLogin, apiKey }; }).pipe( - Effect.flatMap(({ credential, apiKey }) => + Effect.flatMap(({ storedLogin, apiKey }) => checkCursorProviderStatus( effectiveConfig, { @@ -231,15 +228,15 @@ export const CursorDriver: ProviderDriver< Effect.flatMap((snapshot) => effectiveConfig.enabled && snapshot.installed && - (snapshot.auth.status === "authenticated" || - (!auth.usesApiKey && credential.status === "expired")) + // An expired login still probes so the "sign in again" message reaches Usage. + (snapshot.auth.status === "authenticated" || storedLogin?.status === "expired") ? host.settings.get.pipe( Effect.flatMap((settings) => readCursorUsageLimits( effectiveConfig, - auth.usesApiKey ? { ...processEnv, CURSOR_API_KEY: apiKey } : processEnv, + { ...processEnv, CURSOR_API_KEY: apiKey }, settings.cursorKeychainUsageEnabled, - auth.usesApiKey ? undefined : { instanceId, credential }, + storedLogin, ), ), Effect.map((usageLimits) => ({ ...snapshot, usageLimits })), @@ -248,7 +245,6 @@ export const CursorDriver: ProviderDriver< ), ), ), - Effect.provideService(Crypto.Crypto, crypto), Effect.provideService(HttpClient.HttpClient, httpClient), Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), diff --git a/packages/provider-cursor/src/server/usageLimits.test.ts b/packages/provider-cursor/src/server/usageLimits.test.ts index e281a74c78199..4a089ac6be23c 100644 --- a/packages/provider-cursor/src/server/usageLimits.test.ts +++ b/packages/provider-cursor/src/server/usageLimits.test.ts @@ -1,27 +1,17 @@ import { describe, expect, it } from "@effect/vitest"; import { NodeServices } from "@effect/platform-node"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Clock from "effect/Clock"; -import * as Context from "effect/Context"; -import * as TestClock from "effect/testing/TestClock"; -import * as Crypto from "effect/Crypto"; -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import type * as HttpClientRequest from "effect/http/HttpClientRequest"; -import type { CursorCredentialState } from "./auth.ts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as HttpClient from "effect/http/HttpClient"; +import type * as HttpClientRequest from "effect/http/HttpClientRequest"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; import * as CursorKeychain from "./CursorKeychain.ts"; import { cursorUsageResponseToLimits, readCursorUsageLimits } from "./usageLimits.ts"; const withNodeServices = ( - effect: Effect.Effect< - A, - E, - FileSystem.FileSystem | Path.Path | Crypto.Crypto | CursorKeychain.CursorKeychain - >, + effect: Effect.Effect, accessToken: CursorKeychain.CursorKeychain["Service"]["accessToken"] = Effect.die( "must not read Keychain", ), @@ -281,291 +271,91 @@ describe("Cursor usage limits", () => { } }), ); -}); - -const exchangePath = "/auth/exchange_user_api_key"; -const usagePath = "/aiserver.v1.DashboardService/GetCurrentPeriodUsage"; -const storedCredential = { - status: "valid", - apiKey: "private-instance-key", - backendUrl: "https://instance.example/path", -} as const; -const usage = () => Response.json({ planUsage: { totalPercentUsed: 37 } }); -const makeProbe = ( - instanceId: string, - answer: (request: HttpClientRequest.HttpClientRequest, index: number) => Response = (request) => - request.url.endsWith(exchangePath) - ? Response.json({ accessToken: "private-access-token" }) - : usage(), -) => { - const requests: HttpClientRequest.HttpClientRequest[] = []; - const client = HttpClient.make((request, _url, _signal, fiber) => { - expect(Context.getOrUndefined(fiber.context, FetchHttpClient.RequestInit)?.redirect).toBe( - "error", - ); - expect(request.method).toBe("POST"); - expect(request.headers["content-type"]).toBe("application/json"); - expect( - request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : null, - ).toBe("{}"); - requests.push(request); - return Effect.succeed( - HttpClientResponse.fromWeb(request, answer(request, requests.length - 1)), - ); - }); - const probe = ( - credential: CursorCredentialState = storedCredential, - environment: NodeJS.ProcessEnv = {}, - ) => - withNodeServices( - readCursorUsageLimits({ apiEndpoint: "https://unrelated.example" }, environment, true, { - instanceId, - credential, - }).pipe( - Effect.provideService(HttpClient.HttpClient, client), - Effect.provideService(HostProcess.Platform, "darwin"), - Effect.provideService( - FileSystem.FileSystem, - FileSystem.makeNoop({ - readFileString: () => Effect.die("must not read host auth"), - }), + describe("T3 browser login", () => { + const exchangeUrl = "https://instance.example/auth/exchange_user_api_key"; + const usageUrl = "https://instance.example/aiserver.v1.DashboardService/GetCurrentPeriodUsage"; + const login = { + status: "valid", + apiKey: "stored-browser-key", + backendUrl: "https://instance.example/path", + } as const; + // A stored login names this instance's account, so host CLI files and Keychain must stay untouched. + const readWithLogin = ( + storedLogin: Parameters[3], + respond: (request: HttpClientRequest.HttpClientRequest) => Response, + ) => { + const requests: Array<{ + url: string; + authorization: string | undefined; + body: string | null; + }> = []; + const read = withNodeServices( + readCursorUsageLimits( + { apiEndpoint: "https://settings.example" }, + { CURSOR_AUTH_TOKEN: "other-host-account-token" }, + true, + storedLogin, + ).pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService( + FileSystem.FileSystem, + FileSystem.makeNoop({ + readFileString: () => Effect.die("must not read the host CLI login"), + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => { + requests.push({ + url: request.url, + authorization: request.headers.authorization, + body: + request.body._tag === "Uint8Array" + ? new TextDecoder().decode(request.body.body) + : null, + }); + return Effect.succeed(HttpClientResponse.fromWeb(request, respond(request))); + }), + ), ), - ), - ); - return { probe, requests }; -}; - -it.effect( - "publishes stored-login limits at its backend origin without reading host credentials", - () => - Effect.gen(function* () { - for (const [index, environment] of [ - {}, - { CURSOR_AUTH_TOKEN: "other-host-account" }, - { AGENT_CLI_CREDENTIAL_STORE: "file" }, - { AGENT_CLI_CREDENTIAL_STORE: "default" }, - ].entries()) { - const harness = makeProbe(`own-login-${index}`); - expect((yield* harness.probe(storedCredential, environment)).windows[0]?.usedPercent).toBe( - 37, - ); - expect( - harness.requests.map((request) => [request.url, request.headers.authorization]), - ).toEqual([ - [`https://instance.example${exchangePath}`, "Bearer private-instance-key"], - [`https://instance.example${usagePath}`, "Bearer private-access-token"], - ]); - expect(harness.requests[1]?.headers["x-cursor-client-type"]).toBe("sdk"); - expect(harness.requests[1]?.headers["connect-protocol-version"]).toBe("1"); - } - }), -); - -it.effect("reports expired credentials as requiring re-login without requests", () => - Effect.gen(function* () { - const harness = makeProbe("expired"); - expect((yield* harness.probe({ status: "expired" })).unavailable).toMatchObject({ - reason: "unsupported", - message: expect.stringContaining("Sign in again"), - }); - expect(harness.requests).toHaveLength(0); - }), -); - -it.effect("reuses a cached token on the next probe", () => - Effect.gen(function* () { - const harness = makeProbe("cache-reuse"); - yield* harness.probe(); - expect((yield* harness.probe()).windows[0]?.usedPercent).toBe(37); - expect(harness.requests.map((request) => request.url)).toEqual([ - `https://instance.example${exchangePath}`, - `https://instance.example${usagePath}`, - `https://instance.example${usagePath}`, - ]); - }), -); - -it.effect("exchanges a new token when the same instance and key change backend origin", () => - Effect.gen(function* () { - const harness = makeProbe("cache-origin-change", (request) => - request.url.endsWith(exchangePath) - ? Response.json({ - accessToken: request.url.startsWith("https://instance.example/") - ? "old-origin-token" - : "new-origin-token", - }) - : usage(), - ); - yield* harness.probe(); - expect( - (yield* harness.probe({ ...storedCredential, backendUrl: "https://new.example/path" })) - .windows[0]?.usedPercent, - ).toBe(37); - expect(harness.requests.map((request) => [request.url, request.headers.authorization])).toEqual( - [ - [`https://instance.example${exchangePath}`, "Bearer private-instance-key"], - [`https://instance.example${usagePath}`, "Bearer old-origin-token"], - [`https://new.example${exchangePath}`, "Bearer private-instance-key"], - [`https://new.example${usagePath}`, "Bearer new-origin-token"], - ], - ); - yield* harness.probe(); - expect(harness.requests.slice(4).map((request) => request.url)).toEqual([ - `https://instance.example${exchangePath}`, - `https://instance.example${usagePath}`, - ]); - }), -); - -it.effect("refreshes a JWT at its seconds-based expiry minus the 60-second margin", () => - Effect.gen(function* () { - const now = yield* Clock.currentTimeMillis; - const exp = Math.floor(now / 1000) + 600; - const jwt = [ - Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString("base64url"), - Buffer.from(JSON.stringify({ exp })).toString("base64url"), - Buffer.from("test-signature").toString("base64url"), - ].join("."); - const harness = makeProbe("jwt-expiry", (request, index) => - request.url.endsWith(exchangePath) - ? Response.json({ accessToken: index === 0 ? jwt : "refreshed-token" }) - : usage(), - ); - yield* harness.probe(); - yield* TestClock.adjust(exp * 1000 - 60_000 - now - 1); - expect((yield* harness.probe()).windows[0]?.usedPercent).toBe(37); - expect(harness.requests.map((request) => request.headers.authorization)).toEqual([ - "Bearer private-instance-key", - `Bearer ${jwt}`, - `Bearer ${jwt}`, - ]); - yield* TestClock.adjust(2); - expect((yield* harness.probe()).windows[0]?.usedPercent).toBe(37); - expect( - harness.requests.slice(3).map((request) => [request.url, request.headers.authorization]), - ).toEqual([ - [`https://instance.example${exchangePath}`, "Bearer private-instance-key"], - [`https://instance.example${usagePath}`, "Bearer refreshed-token"], - ]); - }), -); - -it.effect("re-exchanges a cached-token 401 once and reports a second 401 as probeFailed", () => - Effect.gen(function* () { - for (const retryStatus of [200, 401]) { - const harness = makeProbe(`cached-401-${retryStatus}`, (request, index) => - request.url.endsWith(exchangePath) - ? Response.json({ accessToken: `access-${index}` }) - : index === 2 || (index === 4 && retryStatus === 401) - ? new Response("private-response", { status: 401 }) - : usage(), ); - yield* harness.probe(); - const result = yield* harness.probe(); - expect(harness.requests.map((request) => request.url.split("/").at(-1))).toEqual([ - "exchange_user_api_key", - "GetCurrentPeriodUsage", - "GetCurrentPeriodUsage", - "exchange_user_api_key", - "GetCurrentPeriodUsage", - ]); - expect(harness.requests[4]?.headers.authorization).toBe("Bearer access-3"); - if (retryStatus === 200) expect(result.windows[0]?.usedPercent).toBe(37); - else expect(result.unavailable?.reason).toBe("probeFailed"); - } - }), -); + return { read, requests }; + }; -it.effect("handles exchange rejection, rate limits and redirects without retries", () => - Effect.gen(function* () { - for (const [status, reason] of [ - [401, "unsupported"], - [429, "probeFailed"], - [302, "probeFailed"], - ] as const) { - const harness = makeProbe( - `exchange-${status}`, - () => - new Response("private-response", { - status, - headers: { location: "https://redirect.example" }, - }), - ); - const result = yield* harness.probe(); - expect(result.unavailable?.reason).toBe(reason); - expect(harness.requests).toHaveLength(1); - expect(JSON.stringify(result)).not.toContain("private-response"); - } - }), -); - -it.effect("refuses insecure and userinfo backends with zero requests", () => - Effect.gen(function* () { - const harness = makeProbe("invalid-backends"); - for (const backendUrl of [ - "http://instance.example", - "https://user@instance.example", - "https://user:password@instance.example", - ]) { - expect((yield* harness.probe({ ...storedCredential, backendUrl })).unavailable?.reason).toBe( - "probeFailed", - ); - } - expect(harness.requests).toHaveLength(0); - }), -); - -it.effect("isolates instance caches and prunes the old key on rotation", () => - Effect.gen(function* () { - const first = makeProbe("cache-first"); - const second = makeProbe("cache-second"); - yield* first.probe(); - yield* second.probe(); - yield* first.probe(); - yield* second.probe(); - expect(first.requests).toHaveLength(3); - expect(second.requests).toHaveLength(3); - yield* first.probe({ ...storedCredential, apiKey: "rotated-key" }); - yield* first.probe(); - expect(first.requests.slice(3).map((request) => request.url)).toEqual([ - `https://instance.example${exchangePath}`, - `https://instance.example${usagePath}`, - `https://instance.example${exchangePath}`, - `https://instance.example${usagePath}`, - ]); - yield* second.probe(); - expect(second.requests).toHaveLength(4); - }), -); - -it.effect("keeps secrets out of usage failure strings", () => - Effect.gen(function* () { - const harness = makeProbe("secret-output", (request) => - request.url.endsWith(exchangePath) - ? Response.json({ - accessToken: "private-access-token", - refreshToken: "private-refresh-token", - }) - : new Response("private-response-body", { status: 500 }), + it.effect( + "exchanges the stored key at the stored backend and reads usage with the result", + () => + Effect.gen(function* () { + const { read, requests } = readWithLogin(login, (request) => + request.url === exchangeUrl + ? Response.json({ accessToken: "exchanged-access-token" }) + : Response.json({ planUsage: { totalPercentUsed: 37 } }), + ); + expect((yield* read).windows[0]?.usedPercent).toBe(37); + expect(requests).toEqual([ + { url: exchangeUrl, authorization: "Bearer stored-browser-key", body: "{}" }, + { url: usageUrl, authorization: "Bearer exchanged-access-token", body: "{}" }, + ]); + }), ); - const result = yield* harness.probe(); - expect(harness.requests.map((request) => [request.url, request.headers.authorization])).toEqual( - [ - [`https://instance.example${exchangePath}`, "Bearer private-instance-key"], - [`https://instance.example${usagePath}`, "Bearer private-access-token"], - ], + + it.effect( + "asks to sign in again for an expired or rejected login without using host logins", + () => + Effect.gen(function* () { + const expired = readWithLogin({ status: "expired" }, () => { + throw new Error("must not request usage for an expired login"); + }); + const rejected = readWithLogin(login, () => new Response("rejected", { status: 401 })); + for (const { read } of [expired, rejected]) { + expect((yield* read).unavailable).toEqual({ + reason: "probeFailed", + message: expect.stringContaining("Sign in again"), + }); + } + expect(expired.requests).toEqual([]); + expect(rejected.requests.map((request) => request.url)).toEqual([exchangeUrl]); + }), ); - expect(result.unavailable).toEqual({ - reason: "probeFailed", - message: "Cursor could not read usage limits.", - }); - const output = JSON.stringify(result); - for (const secret of [ - "private-instance-key", - "private-access-token", - "private-refresh-token", - "private-response-body", - ]) - expect(output).not.toContain(secret); - }), -); + }); +}); diff --git a/packages/provider-cursor/src/server/usageLimits.ts b/packages/provider-cursor/src/server/usageLimits.ts index 21d6159d7af14..ce81ec318bbae 100644 --- a/packages/provider-cursor/src/server/usageLimits.ts +++ b/packages/provider-cursor/src/server/usageLimits.ts @@ -2,11 +2,6 @@ import type { ServerProviderUsageWindow } from "@t3tools/contracts"; import type { CursorSettings } from "../settings.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { CURSOR_USAGE_WINDOWS } from "@t3tools/shared/usageLimits"; -import * as Clock from "effect/Clock"; -import * as Crypto from "effect/Crypto"; -import * as Base64Url from "effect/encoding/Base64Url"; -import * as Hex from "effect/encoding/Hex"; -import * as Result from "effect/Result"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -14,7 +9,6 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import type { CursorCredentialState } from "./auth.ts"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientRequest from "effect/http/HttpClientRequest"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; @@ -24,6 +18,7 @@ import { makeUsageLimits, } from "@t3tools/provider-core/server/usageLimits"; import * as CursorKeychain from "./CursorKeychain.ts"; +import type { CursorStoredLogin } from "./auth.ts"; const CursorCredentials = Schema.Struct({ accessToken: Schema.optional(Schema.String) }); const DEFAULT_CURSOR_API_ENDPOINT = "https://api2.cursor.sh"; @@ -68,162 +63,77 @@ export function cursorUsageResponseToLimits( : makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); } -interface UsageToken { - readonly accessToken: string; - readonly expiresAtMs: number; -} -const tokens = new Map(); -const exchanges = new Map< - string, - Effect.Effect< - UsageToken | undefined, - Effect.Error>, - HttpClient.HttpClient - > ->(); +const ExchangedAccessToken = Schema.Struct({ accessToken: Schema.NonEmptyString }); -function pruneCursorUsageTokens(instanceId: string, keepKey?: string): void { - for (const entries of [tokens, exchanges]) { - for (const existing of entries.keys()) { - if (existing.startsWith(`${instanceId.length}:${instanceId}:`) && existing !== keepKey) - entries.delete(existing); - } - } -} - -const decodeTokenClaims = Schema.decodeOption( - Schema.fromJsonString(Schema.Struct({ exp: Schema.Number })), -); - -function tokenExpiresAt(accessToken: string, now: number): number { - const parts = accessToken.split("."); - if (parts.length !== 3) return now + 300_000; - const decoded = Base64Url.decodeString(parts[1]!); - if (Result.isFailure(decoded)) return now + 300_000; - // JWT claims only bound the cache lifetime; the backend validates the bearer. - const claims = decodeTokenClaims(decoded.success); - if (Option.isSome(claims)) { - const expiresAtMs = claims.value.exp * 1000 - 60_000; - if (Number.isFinite(expiresAtMs)) return expiresAtMs; - } - return now + 300_000; -} - -const exchangeToken = (endpoint: string, apiKey: string) => +const requestUsage = (endpoint: string, token: string, clientType: "cli" | "sdk") => Effect.gen(function* () { const client = yield* HttpClient.HttpClient; const response = yield* client.execute( - HttpClientRequest.post(`${endpoint}/auth/exchange_user_api_key`).pipe( - HttpClientRequest.bearerToken(apiKey), + HttpClientRequest.post(`${endpoint}/aiserver.v1.DashboardService/GetCurrentPeriodUsage`).pipe( + HttpClientRequest.bearerToken(token), + HttpClientRequest.setHeaders({ + "connect-protocol-version": "1", + "x-cursor-client-type": clientType, + }), HttpClientRequest.bodyJsonUnsafe({}), ), ); - if (response.status === 401) return undefined; - const body = yield* HttpClientResponse.schemaBodyJson( - Schema.Struct({ accessToken: Schema.NonEmptyString }), - )(yield* HttpClientResponse.filterStatusOk(response)); - return { - accessToken: body.accessToken, - expiresAtMs: tokenExpiresAt(body.accessToken, yield* Clock.currentTimeMillis), - }; + return yield* HttpClientResponse.schemaBodyJson(CursorUsageResponse)( + yield* HttpClientResponse.filterStatusOk(response), + ); }); -const getInstanceToken = (key: string, endpoint: string, apiKey: string) => - Effect.gen(function* () { - const pending = exchanges.get(key); - if (pending) return yield* pending; - const operation = yield* Effect.cached( - exchangeToken(endpoint, apiKey).pipe( - Effect.tap((token) => - Effect.sync(() => { - // A rotated or logged-out instance must not be repopulated by an older exchange. - if (token && exchanges.get(key) === operation) tokens.set(key, token); - }), - ), - Effect.ensuring( - Effect.sync(() => { - if (exchanges.get(key) === operation) exchanges.delete(key); - }), - ), - ), - ); - exchanges.set(key, operation); - return yield* operation; +const signInAgain = (checkedAt: string) => + makeUnavailableUsageLimits({ + checkedAt, + reason: "probeFailed", + message: "Cursor sign-in expired or was rejected. Sign in again in provider settings.", }); -const readInstanceUsage = ( - instanceId: string, - credential: CursorCredentialState, - checkedAt: string, -) => +/** + * The stored browser login is a user API key, which the dashboard rejects as a bearer. Like + * `@cursor/sdk`, exchange it for a short-lived access token at the login's own backend first. + */ +const readStoredLoginUsage = (login: CursorStoredLogin, checkedAt: string) => Effect.gen(function* () { - if (credential.status !== "valid") pruneCursorUsageTokens(instanceId); - const authRequired = () => - makeUnavailableUsageLimits({ - checkedAt, - reason: "unsupported", - message: "Cursor sign-in expired or was rejected. Sign in again in provider settings.", - }); - if (credential.status === "absent") return undefined; - if (credential.status === "expired") return authRequired(); + if (login.status === "expired") return signInAgain(checkedAt); const endpoint = yield* Effect.try(() => { - const url = new URL(credential.backendUrl); - if (url.protocol !== "https:" || url.username || url.password) - throw new Error("Invalid Cursor credential backend."); + const url = new URL(login.backendUrl); + if (url.protocol !== "https:" || url.username || url.password) { + throw new Error("Cursor login backend must be a plain https origin."); + } return url.origin; }); - const crypto = yield* Crypto.Crypto; - const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(credential.apiKey)); - const key = `${instanceId.length}:${instanceId}:${endpoint}:${Hex.encode(digest)}`; - pruneCursorUsageTokens(instanceId, key); - const now = yield* Clock.currentTimeMillis; - const cached = tokens.get(key); - const usable = cached && cached.expiresAtMs > now ? cached : undefined; - if (!usable) tokens.delete(key); - let token = usable ?? (yield* getInstanceToken(key, endpoint, credential.apiKey)); - if (!token) return authRequired(); const client = yield* HttpClient.HttpClient; - const requestUsage = (accessToken: string) => - client.execute( - HttpClientRequest.post( - `${endpoint}/aiserver.v1.DashboardService/GetCurrentPeriodUsage`, - ).pipe( - HttpClientRequest.bearerToken(accessToken), - HttpClientRequest.setHeaders({ - "connect-protocol-version": "1", - "x-cursor-client-type": "sdk", - }), - HttpClientRequest.bodyJsonUnsafe({}), - ), - ); - let response = yield* requestUsage(token.accessToken); - if (response.status === 401) { - if (tokens.get(key) === token) tokens.delete(key); - if (usable) { - token = yield* getInstanceToken(key, endpoint, credential.apiKey); - if (!token) return authRequired(); - response = yield* requestUsage(token.accessToken); - if (response.status === 401 && tokens.get(key) === token) tokens.delete(key); - } - } - const body = yield* HttpClientResponse.schemaBodyJson(CursorUsageResponse)( - yield* HttpClientResponse.filterStatusOk(response), + const exchange = yield* client.execute( + HttpClientRequest.post(`${endpoint}/auth/exchange_user_api_key`).pipe( + HttpClientRequest.bearerToken(login.apiKey), + HttpClientRequest.bodyJsonUnsafe({}), + ), + ); + if (exchange.status === 401) return signInAgain(checkedAt); + const { accessToken } = yield* HttpClientResponse.schemaBodyJson(ExchangedAccessToken)( + yield* HttpClientResponse.filterStatusOk(exchange), + ); + return cursorUsageResponseToLimits( + yield* requestUsage(endpoint, accessToken, "sdk"), + checkedAt, ); - return cursorUsageResponseToLimits(body, checkedAt); - }).pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" })); + }).pipe( + // A redirect would carry the user's key to another host. + Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }), + ); export const readCursorUsageLimits = Effect.fn("readCursorUsageLimits")(function* ( settings: Pick, environment: NodeJS.ProcessEnv = process.env, allowKeychain = false, - instance?: { readonly instanceId: string; readonly credential: CursorCredentialState }, + storedLogin?: CursorStoredLogin, ) { const checkedAt = DateTime.formatIso(yield* DateTime.now); return yield* Effect.gen(function* () { - if (instance) { - const limits = yield* readInstanceUsage(instance.instanceId, instance.credential, checkedAt); - if (limits) return limits; - } + // A login saved by T3 names this instance's account; host CLI logins may belong to another. + if (storedLogin) return yield* readStoredLoginUsage(storedLogin, checkedAt); const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const platform = yield* HostProcess.Platform; @@ -282,21 +192,7 @@ export const readCursorUsageLimits = Effect.fn("readCursorUsageLimits")(function token = credentials.accessToken?.trim(); } if (!token) return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); - const client = yield* HttpClient.HttpClient; - const response = yield* client.execute( - HttpClientRequest.post(`${endpoint}/aiserver.v1.DashboardService/GetCurrentPeriodUsage`).pipe( - HttpClientRequest.bearerToken(token), - HttpClientRequest.setHeaders({ - "connect-protocol-version": "1", - "x-cursor-client-type": "cli", - }), - HttpClientRequest.bodyJsonUnsafe({}), - ), - ); - const body = yield* HttpClientResponse.schemaBodyJson(CursorUsageResponse)( - yield* HttpClientResponse.filterStatusOk(response), - ); - return cursorUsageResponseToLimits(body, checkedAt); + return cursorUsageResponseToLimits(yield* requestUsage(endpoint, token, "cli"), checkedAt); }).pipe( Effect.timeout("10 seconds"), Effect.orElseSucceed(() => From 4f45a6c209d6b60b0c127579ff42c9e8cf052990 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 02:17:26 +0000 Subject: [PATCH 4/6] fix(cursor): surface usage failures beside retained limits --- .../provider-cursor/src/server/driver.test.ts | 19 ++++++++++++++----- packages/provider-cursor/src/server/driver.ts | 15 ++++++++++++++- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/packages/provider-cursor/src/server/driver.test.ts b/packages/provider-cursor/src/server/driver.test.ts index 4873f74a13501..a6296cd18e7a1 100644 --- a/packages/provider-cursor/src/server/driver.test.ts +++ b/packages/provider-cursor/src/server/driver.test.ts @@ -94,6 +94,7 @@ it.layer(layerTest)("CursorDriver", (it) => { const openedKeys: Array = []; let closed = 0; const requests: string[] = []; + let rejectExchange = false; const usageClient = HttpClient.make((request) => { requests.push(request.url); const exchange = request.url.endsWith("/auth/exchange_user_api_key"); @@ -103,11 +104,13 @@ it.layer(layerTest)("CursorDriver", (it) => { return Effect.succeed( HttpClientResponse.fromWeb( request, - Response.json( - exchange - ? { accessToken: "browser-access-token" } - : { planUsage: { totalPercentUsed: 23 } }, - ), + exchange && rejectExchange + ? new Response(null, { status: 401 }) + : Response.json( + exchange + ? { accessToken: "browser-access-token" } + : { planUsage: { totalPercentUsed: 23 } }, + ), ), ); }); @@ -172,6 +175,12 @@ it.layer(layerTest)("CursorDriver", (it) => { Effect.provideService(HttpClient.HttpClient, usageClient), ); expect((yield* recreated.snapshot.refresh).auth.status).toBe("authenticated"); + rejectExchange = true; + expect(yield* instance.snapshot.refresh).toMatchObject({ + status: "warning", + message: expect.stringContaining("Sign in again"), + usageLimits: { windows: [{ id: "totalPercentUsed", usedPercent: 23 }] }, + }); yield* instance.auth!.logout(Effect.void); expect(closed).toBe(1); expect((yield* instance.snapshot.getSnapshot).auth.status).toBe("unauthenticated"); diff --git a/packages/provider-cursor/src/server/driver.ts b/packages/provider-cursor/src/server/driver.ts index 34f675f4c9500..5714ea72b2543 100644 --- a/packages/provider-cursor/src/server/driver.ts +++ b/packages/provider-cursor/src/server/driver.ts @@ -239,7 +239,20 @@ export const CursorDriver: ProviderDriver< storedLogin, ), ), - Effect.map((usageLimits) => ({ ...snapshot, usageLimits })), + Effect.map((usageLimits) => { + const notice = usageLimits.unavailable; + // Managed snapshots retain last good limits, so failures also need a provider message. + return { + ...snapshot, + usageLimits, + ...(notice?.reason === "probeFailed" && notice.message + ? { + status: snapshot.status === "ready" ? "warning" : snapshot.status, + message: [snapshot.message, notice.message].filter(Boolean).join(" "), + } + : {}), + }; + }), ) : Effect.succeed(snapshot), ), From 8256cd2637664343e9d01d1b370c6c5b8a02d37c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 02:29:32 +0000 Subject: [PATCH 5/6] fix(cursor): keep usage failures separate from provider readiness --- .../provider-cursor/src/server/driver.test.ts | 38 +++++++++++++++---- packages/provider-cursor/src/server/driver.ts | 18 +-------- .../src/server/usageLimits.test.ts | 19 ++++++++-- .../provider-cursor/src/server/usageLimits.ts | 2 +- 4 files changed, 49 insertions(+), 28 deletions(-) diff --git a/packages/provider-cursor/src/server/driver.test.ts b/packages/provider-cursor/src/server/driver.test.ts index a6296cd18e7a1..28f1dada0fef9 100644 --- a/packages/provider-cursor/src/server/driver.test.ts +++ b/packages/provider-cursor/src/server/driver.test.ts @@ -94,7 +94,8 @@ it.layer(layerTest)("CursorDriver", (it) => { const openedKeys: Array = []; let closed = 0; const requests: string[] = []; - let rejectExchange = false; + let failureUrl: string | undefined; + let failureStatus = 500; const usageClient = HttpClient.make((request) => { requests.push(request.url); const exchange = request.url.endsWith("/auth/exchange_user_api_key"); @@ -104,8 +105,8 @@ it.layer(layerTest)("CursorDriver", (it) => { return Effect.succeed( HttpClientResponse.fromWeb( request, - exchange && rejectExchange - ? new Response(null, { status: 401 }) + request.url === failureUrl + ? new Response(null, { status: failureStatus }) : Response.json( exchange ? { accessToken: "browser-access-token" } @@ -175,12 +176,35 @@ it.layer(layerTest)("CursorDriver", (it) => { Effect.provideService(HttpClient.HttpClient, usageClient), ); expect((yield* recreated.snapshot.refresh).auth.status).toBe("authenticated"); - rejectExchange = true; + for (const url of requests.slice(0, 2)) { + failureUrl = url; + const snapshot = yield* instance.snapshot.refresh; + expect(snapshot).toMatchObject({ + status: "ready", + auth: { status: "authenticated" }, + usageLimits: { windows: [{ id: "totalPercentUsed", usedPercent: 23 }] }, + }); + expect(snapshot.message).toBeUndefined(); + } + failureUrl = requests[0]; + failureStatus = 401; expect(yield* instance.snapshot.refresh).toMatchObject({ - status: "warning", - message: expect.stringContaining("Sign in again"), - usageLimits: { windows: [{ id: "totalPercentUsed", usedPercent: 23 }] }, + status: "ready", + auth: { status: "authenticated" }, + usageLimits: { windows: [], unavailable: { reason: "unsupported" } }, + }); + failureUrl = undefined; + expect((yield* instance.snapshot.refresh).usageLimits?.windows[0]?.usedPercent).toBe(23); + const { store } = yield* makeCursorCredentialStore(input.instanceId); + yield* Effect.promise(async () => { + const credentials = await store.load(); + await store.save({ ...credentials!, apiKeyExpiresAtMs: 0 }); }); + const requestCount = requests.length; + const expired = yield* instance.snapshot.refresh; + expect(expired.auth.status).toBe("unauthenticated"); + expect(expired.usageLimits).toBeUndefined(); + expect(requests).toHaveLength(requestCount); yield* instance.auth!.logout(Effect.void); expect(closed).toBe(1); expect((yield* instance.snapshot.getSnapshot).auth.status).toBe("unauthenticated"); diff --git a/packages/provider-cursor/src/server/driver.ts b/packages/provider-cursor/src/server/driver.ts index 5714ea72b2543..ec07728862140 100644 --- a/packages/provider-cursor/src/server/driver.ts +++ b/packages/provider-cursor/src/server/driver.ts @@ -228,8 +228,7 @@ export const CursorDriver: ProviderDriver< Effect.flatMap((snapshot) => effectiveConfig.enabled && snapshot.installed && - // An expired login still probes so the "sign in again" message reaches Usage. - (snapshot.auth.status === "authenticated" || storedLogin?.status === "expired") + snapshot.auth.status === "authenticated" ? host.settings.get.pipe( Effect.flatMap((settings) => readCursorUsageLimits( @@ -239,20 +238,7 @@ export const CursorDriver: ProviderDriver< storedLogin, ), ), - Effect.map((usageLimits) => { - const notice = usageLimits.unavailable; - // Managed snapshots retain last good limits, so failures also need a provider message. - return { - ...snapshot, - usageLimits, - ...(notice?.reason === "probeFailed" && notice.message - ? { - status: snapshot.status === "ready" ? "warning" : snapshot.status, - message: [snapshot.message, notice.message].filter(Boolean).join(" "), - } - : {}), - }; - }), + Effect.map((usageLimits) => ({ ...snapshot, usageLimits })), ) : Effect.succeed(snapshot), ), diff --git a/packages/provider-cursor/src/server/usageLimits.test.ts b/packages/provider-cursor/src/server/usageLimits.test.ts index 4a089ac6be23c..665a37d047060 100644 --- a/packages/provider-cursor/src/server/usageLimits.test.ts +++ b/packages/provider-cursor/src/server/usageLimits.test.ts @@ -340,7 +340,7 @@ describe("Cursor usage limits", () => { ); it.effect( - "asks to sign in again for an expired or rejected login without using host logins", + "clears expired or rejected login usage and reports transient failures without using host logins", () => Effect.gen(function* () { const expired = readWithLogin({ status: "expired" }, () => { @@ -348,11 +348,22 @@ describe("Cursor usage limits", () => { }); const rejected = readWithLogin(login, () => new Response("rejected", { status: 401 })); for (const { read } of [expired, rejected]) { - expect((yield* read).unavailable).toEqual({ - reason: "probeFailed", - message: expect.stringContaining("Sign in again"), + expect(yield* read).toMatchObject({ + windows: [], + unavailable: { + reason: "unsupported", + message: expect.stringContaining("Sign in again"), + }, }); } + for (const failedUrl of [exchangeUrl, usageUrl]) { + const transient = readWithLogin(login, (request) => + request.url === failedUrl + ? new Response(null, { status: 500 }) + : Response.json({ accessToken: "exchanged-access-token" }), + ); + expect((yield* transient.read).unavailable?.reason).toBe("probeFailed"); + } expect(expired.requests).toEqual([]); expect(rejected.requests.map((request) => request.url)).toEqual([exchangeUrl]); }), diff --git a/packages/provider-cursor/src/server/usageLimits.ts b/packages/provider-cursor/src/server/usageLimits.ts index ce81ec318bbae..d25653174c718 100644 --- a/packages/provider-cursor/src/server/usageLimits.ts +++ b/packages/provider-cursor/src/server/usageLimits.ts @@ -86,7 +86,7 @@ const requestUsage = (endpoint: string, token: string, clientType: "cli" | "sdk" const signInAgain = (checkedAt: string) => makeUnavailableUsageLimits({ checkedAt, - reason: "probeFailed", + reason: "unsupported", message: "Cursor sign-in expired or was rejected. Sign in again in provider settings.", }); From fce6e00104ca0f746f3935d1f68fa9bbc6cc66aa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 20 Oct 2026 06:44:13 +0000 Subject: [PATCH 6/6] fix(cursor): use Effect.fn for usage requests Co-Authored-By: Claude Opus 5.5 --- .../provider-cursor/src/server/usageLimits.ts | 49 ++++++++++--------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/packages/provider-cursor/src/server/usageLimits.ts b/packages/provider-cursor/src/server/usageLimits.ts index d25653174c718..a1ca88a548a03 100644 --- a/packages/provider-cursor/src/server/usageLimits.ts +++ b/packages/provider-cursor/src/server/usageLimits.ts @@ -65,23 +65,26 @@ export function cursorUsageResponseToLimits( const ExchangedAccessToken = Schema.Struct({ accessToken: Schema.NonEmptyString }); -const requestUsage = (endpoint: string, token: string, clientType: "cli" | "sdk") => - Effect.gen(function* () { - const client = yield* HttpClient.HttpClient; - const response = yield* client.execute( - HttpClientRequest.post(`${endpoint}/aiserver.v1.DashboardService/GetCurrentPeriodUsage`).pipe( - HttpClientRequest.bearerToken(token), - HttpClientRequest.setHeaders({ - "connect-protocol-version": "1", - "x-cursor-client-type": clientType, - }), - HttpClientRequest.bodyJsonUnsafe({}), - ), - ); - return yield* HttpClientResponse.schemaBodyJson(CursorUsageResponse)( - yield* HttpClientResponse.filterStatusOk(response), - ); - }); +const requestUsage = Effect.fn("CursorUsageLimits.requestUsage")(function* ( + endpoint: string, + token: string, + clientType: "cli" | "sdk", +) { + const client = yield* HttpClient.HttpClient; + const response = yield* client.execute( + HttpClientRequest.post(`${endpoint}/aiserver.v1.DashboardService/GetCurrentPeriodUsage`).pipe( + HttpClientRequest.bearerToken(token), + HttpClientRequest.setHeaders({ + "connect-protocol-version": "1", + "x-cursor-client-type": clientType, + }), + HttpClientRequest.bodyJsonUnsafe({}), + ), + ); + return yield* HttpClientResponse.schemaBodyJson(CursorUsageResponse)( + yield* HttpClientResponse.filterStatusOk(response), + ); +}); const signInAgain = (checkedAt: string) => makeUnavailableUsageLimits({ @@ -94,8 +97,8 @@ const signInAgain = (checkedAt: string) => * The stored browser login is a user API key, which the dashboard rejects as a bearer. Like * `@cursor/sdk`, exchange it for a short-lived access token at the login's own backend first. */ -const readStoredLoginUsage = (login: CursorStoredLogin, checkedAt: string) => - Effect.gen(function* () { +const readStoredLoginUsage = Effect.fn("CursorUsageLimits.readStoredLoginUsage")( + function* (login: CursorStoredLogin, checkedAt: string) { if (login.status === "expired") return signInAgain(checkedAt); const endpoint = yield* Effect.try(() => { const url = new URL(login.backendUrl); @@ -119,10 +122,10 @@ const readStoredLoginUsage = (login: CursorStoredLogin, checkedAt: string) => yield* requestUsage(endpoint, accessToken, "sdk"), checkedAt, ); - }).pipe( - // A redirect would carry the user's key to another host. - Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }), - ); + }, + // A redirect would carry the user's key to another host. + Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }), +); export const readCursorUsageLimits = Effect.fn("readCursorUsageLimits")(function* ( settings: Pick,