From 36d890260117b99a7348f2c133a0045675c88d29 Mon Sep 17 00:00:00 2001 From: Kun Song Date: Sun, 25 Oct 2026 02:37:12 -0700 Subject: [PATCH] cursor 0.2.23: send cursor-agent's team in x-cursor-team-id (#231) cursor-agent sends the team a request is billed to in `x-cursor-team-id`, from cli-config.json's `authInfo.activeTeamId`. Without it, Cursor takes the token's default team. In an organization that team may have on-demand spend turned off, and the request then fails with "Team budget limit reached". The plugin now sends the same header on Run (both the native and the stateless path) and on the dashboard calls. It takes the team only when the token's `sub` is the config's `authInfo.authId`, so an account signed in from magpie never gets another account's team. GetHardLimit and GetCurrentPeriodUsage still go out with `{}`, as cursor-agent sends them. GetFilteredUsageEvents names the team only when there is one. The config's location (CURSOR_CONFIG_DIR, then $XDG_CONFIG_HOME/cursor, then ~/.cursor) and the team check (a positive integer) match cursor-agent 2026.10.01's paths.js and request.js. Run at d4476ff merged onto main 1fbe22b, in a sandbox HOME, with the network pointed at a dead proxy: - `bun test` (whole repo): 2640 pass, 0 fail. `bun test packages/cursor`: 303 pass. `bun scripts/check.mjs cursor`: ok. - Broke each change by hand, and team-id.test.mjs went red each time (11 pass, 1 fail): the header removed from runNative, the header removed from runOnce, and the team put back into GetCurrentPeriodUsage's body. - Real Cursor account (no team) through the plugin's loader: one chat turn with a config that has no team, and one whose activeTeamId is a team the account isn't in. Both returned 200 "ok", so a single-team account is unchanged. The author ran a real account in two teams: the budget-spent team returned 429, the other returned 200. Not tried: a multi-team account here. Accounts signed in from magpie get no team (#233 covers those). Co-authored-by: bborn2 --- packages/cursor/index.mjs | 73 +++++++++- packages/cursor/package.json | 2 +- packages/cursor/team-id.test.mjs | 243 +++++++++++++++++++++++++++++++ 3 files changed, 313 insertions(+), 5 deletions(-) create mode 100644 packages/cursor/team-id.test.mjs diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index d0a4f7f..fe1f825 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -117,6 +117,68 @@ function authFile() { return join(process.env.XDG_CONFIG_HOME || join(home, ".config"), "cursor", "auth.json") } +// cliConfigFile is cursor-agent's cli-config.json, where it keeps the team +// it signed in to (authInfo.activeTeamId); its directory found as the CLI +// finds it, on every OS. +function cliConfigFile() { + const dir = process.env.CURSOR_CONFIG_DIR?.trim() + || (process.env.XDG_CONFIG_HOME?.trim() ? join(process.env.XDG_CONFIG_HOME, "cursor") : join(homedir(), ".cursor")) + return join(dir, "cli-config.json") +} + +// tokenSub is a JWT's subject (the auth id, "auth0|user_…"); "" when it +// doesn't say. +function tokenSub(tok) { + const parts = String(tok ?? "").split(".") + if (parts.length !== 3) return "" + try { + const sub = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"))?.sub + return typeof sub === "string" ? sub : "" + } catch { + return "" + } +} + +const teamOf = (v) => (Number.isSafeInteger(v) && v > 0 ? v : undefined) + +// activeTeamId is the team a request is billed to, as cursor-agent sends it +// (x-cursor-team-id): cli-config.json's authInfo.activeTeamId. Without it +// Cursor takes the token's default team, which in an organization may be one +// with on-demand spend turned off ("Team budget limit reached"). The config's +// team is only taken for the account cursor-agent signed in to: a token +// whose subject isn't its authInfo.authId, or a config with none, gets none. +// Read again after 10 s; cursor-agent rewrites the file in place, so a read +// that fails to parse keeps the last one, and only a missing file clears it. +const TEAM_TTL = 10_000 +const teamRead = { at: 0, info: null } +async function activeTeamId(tok) { + if (Date.now() - teamRead.at >= TEAM_TTL) { + try { + teamRead.info = JSON.parse(await readFile(cliConfigFile(), "utf8"))?.authInfo ?? null + } catch (e) { + if (e?.code === "ENOENT") teamRead.info = null + } + teamRead.at = Date.now() + } + const info = teamRead.info + if (!info) return undefined + if (!info.authId || info.authId !== tokenSub(tok)) return undefined + return teamOf(info.activeTeamId) +} + +// teamHeader names that team in a request's headers, and teamBody in +// GetFilteredUsageEvents' body; neither says anything when there is none. +// GetHardLimit and GetCurrentPeriodUsage go out with "{}", as cursor-agent +// sends them: the team rides in the header only. +async function teamHeader(tok) { + const id = await activeTeamId(tok) + return id ? { "x-cursor-team-id": String(id) } : {} +} +async function teamBody(tok) { + const id = await activeTeamId(tok) + return id ? { teamId: id } : {} +} + // TOKEN_TTL is how long a token read from the Keychain is taken as it: a // sign-in reads it afresh, one made in cursor-agent is seen within it. // KEYCHAIN_DENIED is how long a read the user may have been asked about, @@ -218,6 +280,7 @@ async function headersFor(tok) { "x-cursor-client-version": await clientVersion(), "x-cursor-client-type": "cli", "x-ghost-mode": "true", + ...await teamHeader(tok), } } @@ -456,7 +519,7 @@ async function hardLimit(tok) { try { const res = await fetch(API + "/aiserver.v1.DashboardService/GetHardLimit", { method: "POST", - headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1" }, + headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1", ...await teamHeader(tok) }, body: "{}", signal: AbortSignal.timeout(15_000), }) @@ -481,7 +544,7 @@ async function usage(tok, ids) { const [res, hard] = await Promise.all([ fetch(API + "/aiserver.v1.DashboardService/GetCurrentPeriodUsage", { method: "POST", - headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1" }, + headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1", ...await teamHeader(tok) }, body: "{}", signal: AbortSignal.timeout(15_000), }), @@ -1515,7 +1578,7 @@ async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_ const res = await fetch(API + "/aiserver.v1.DashboardService/GetFilteredUsageEvents", { method: "POST", headers: await headersFor(tok), - body: JSON.stringify({ teamId: 0, startDate: String(since - 60_000), endDate: String(Date.now() + 60_000), page: 1, pageSize: 50 }), + body: JSON.stringify({ ...await teamBody(tok), startDate: String(since - 60_000), endDate: String(Date.now() + 60_000), page: 1, pageSize: 50 }), signal: abortFetch && signal ? AbortSignal.any([signal, AbortSignal.timeout(STEP_WAIT.ask)]) : AbortSignal.timeout(STEP_WAIT.ask), }) if (res.status >= 400 && res.status < 500 && res.status !== 429) { @@ -2149,6 +2212,7 @@ async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode, "x-cursor-client-type": "cli", // else Cursor adds a prompt of its own "x-ghost-mode": "true", // privacy mode: nothing kept for training "x-request-id": randomUUID(), + ...await teamHeader(tok), // none of Cursor's own tools, only the caller's "x-cursor-agent-allowed-tools": "mcp_tool_call,get_mcp_tools_tool_call", }, @@ -2237,6 +2301,7 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa "x-cursor-client-type": "cli", // else Cursor adds a prompt of its own "x-ghost-mode": "true", // privacy mode: nothing kept for training "x-request-id": randomUUID(), + ...await teamHeader(tok), // none of Cursor's own tools, only the caller's "x-cursor-agent-allowed-tools": "mcp_tool_call,get_mcp_tools_tool_call", }, @@ -2887,4 +2952,4 @@ export async function CursorAuthPlugin() { } // for tests -export const _internal = { keychain, keychainToken, nativeTransport, onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, H2, H1, h2Blocked, open, openH1, openH2, STEP_WAIT, stepUsage, usageKey, ledger, owed, flights, misses, unreadable, catalog, usable, request, modelsOf, tokensOf, maxRequired, conversationID, usageOf, sessionOf, SESSION, errorResponse, kept, poolBase, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } +export const _internal = { keychain, keychainToken, nativeTransport, onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, resetTeam: () => { teamRead.at = 0; teamRead.info = null }, expireTeam: () => (teamRead.at = 0),H2, H1, h2Blocked, open, openH1, openH2, STEP_WAIT, stepUsage, usageKey, ledger, owed, flights, misses, unreadable, catalog, usable, request, modelsOf, tokensOf, maxRequired, conversationID, usageOf, sessionOf, SESSION, errorResponse, kept, poolBase, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } diff --git a/packages/cursor/package.json b/packages/cursor/package.json index 364c938..bdbf59a 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.2.22", + "version": "0.2.23", "description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to", "type": "module", "main": "./index.mjs", diff --git a/packages/cursor/team-id.test.mjs b/packages/cursor/team-id.test.mjs new file mode 100644 index 0000000..3b97f5c --- /dev/null +++ b/packages/cursor/team-id.test.mjs @@ -0,0 +1,243 @@ +// Team ID (x-cursor-team-id header) is sent when cli-config.json has +// authInfo.activeTeamId for the account that signed in (token's sub matches +// authInfo.authId). Without it Cursor uses the token's default team, which +// may have on-demand spend off ("Team budget limit reached"). Tests run in +// a sandbox HOME so the real ~/.cursor/cli-config.json is not read. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import http2 from "node:http2" +import { mkdtemp, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { CursorAuthPlugin, _internal } from "./index.mjs" +import { NATIVE_LIMITS, nativeSessions } from "./native-session.mjs" + +const real = globalThis.fetch +const realEnv = { ...process.env } +const limits = { ...NATIVE_LIMITS } +afterEach(async () => { + await nativeSessions.clear() + Object.assign(NATIVE_LIMITS, limits) + globalThis.fetch = real + process.env = { ...realEnv } + _internal.resetTeam() +}) + +// jwt builds a token with the given subject and expiry +const jwt = (sub, exp) => { + const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString("base64url") + const payload = Buffer.from(JSON.stringify({ sub, exp })).toString("base64url") + return `${header}.${payload}.sig` +} + +const tok1 = jwt("auth0|user_abc", Math.floor(Date.now() / 1000) + 3600) +const tok2 = jwt("auth0|user_xyz", Math.floor(Date.now() / 1000) + 3600) +let n = 0 +const fresh = (sub) => ({ type: "oauth", access: jwt(sub, Math.floor(Date.now() / 1000) + 3600 + ++n), refresh: "", expires: 0, accountId: "a@b.c" }) +const auth1 = { type: "oauth", access: tok1, refresh: "", expires: 0, accountId: "a@b.c" } +const auth2 = { type: "oauth", access: tok2, refresh: "", expires: 0, accountId: "x@y.z" } + +const PERIOD = "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage" +const PLAN = "https://api2.cursor.sh/aiserver.v1.DashboardService/GetPlanInfo" + +async function run(a, configDir, configContent) { + if (configContent !== undefined) { + await writeFile(join(configDir, "cli-config.json"), JSON.stringify(configContent)) + } + process.env.CURSOR_CONFIG_DIR = configDir + _internal.expireTeam() // force re-read of cli-config.json + const seen = [] + globalThis.fetch = async (url, init) => { + seen.push({ url: String(url), method: init.method, headers: init.headers, body: init.body }) + if (String(url) === PLAN) return Response.json({ planInfo: { planName: "Pro" } }) + return Response.json({ billingCycleEnd: "1792833042000", planUsage: { autoPercentUsed: 10, apiPercentUsed: 20, totalPercentUsed: 15 } }) + } + const hooks = await CursorAuthPlugin() + await hooks.auth.usage(async () => a, { models: {} }) + return seen +} + +test("activeTeamId sent in the header, the body left {}, when authId matches token", async () => { + const dir = await mkdtemp(join(tmpdir(), "cursor-team-")) + try { + const config = { authInfo: { authId: "auth0|user_abc", activeTeamId: 42 } } + const seen = await run(auth1, dir, config) + const period = seen.find((r) => r.url === PERIOD) + expect(period.headers["x-cursor-team-id"]).toBe("42") + expect(JSON.parse(period.body)).toEqual({}) + } finally { + await rm(dir, { recursive: true, force: true }) + } +}) + +test("no team header when authId does not match token", async () => { + const dir = await mkdtemp(join(tmpdir(), "cursor-team-")) + try { + const config = { authInfo: { authId: "auth0|user_abc", activeTeamId: 42 } } + const seen = await run(auth2, dir, config) // auth2 has different sub + const period = seen.find((r) => r.url === PERIOD) + expect(period.headers["x-cursor-team-id"]).toBeUndefined() + expect(JSON.parse(period.body)).toEqual({}) + } finally { + await rm(dir, { recursive: true, force: true }) + } +}) + +test("no team header when authId is missing", async () => { + const dir = await mkdtemp(join(tmpdir(), "cursor-team-")) + try { + const config = { authInfo: { activeTeamId: 42 } } // no authId + const seen = await run(auth1, dir, config) + const period = seen.find((r) => r.url === PERIOD) + expect(period.headers["x-cursor-team-id"]).toBeUndefined() + expect(JSON.parse(period.body)).toEqual({}) + } finally { + await rm(dir, { recursive: true, force: true }) + } +}) + +test("no team header when only teamId exists (no activeTeamId)", async () => { + const dir = await mkdtemp(join(tmpdir(), "cursor-team-")) + try { + const config = { authInfo: { authId: "auth0|user_abc", teamId: 99 } } + const seen = await run(auth1, dir, config) + const period = seen.find((r) => r.url === PERIOD) + expect(period.headers["x-cursor-team-id"]).toBeUndefined() + expect(JSON.parse(period.body)).toEqual({}) + } finally { + await rm(dir, { recursive: true, force: true }) + } +}) + +test("no team header when activeTeamId is not a safe integer", async () => { + const dir = await mkdtemp(join(tmpdir(), "cursor-team-")) + try { + const config = { authInfo: { authId: "auth0|user_abc", activeTeamId: "42" } } + const seen = await run(auth1, dir, config) + const period = seen.find((r) => r.url === PERIOD) + expect(period.headers["x-cursor-team-id"]).toBeUndefined() + } finally { + await rm(dir, { recursive: true, force: true }) + } +}) + +test("no team header when activeTeamId is zero or negative", async () => { + const dir = await mkdtemp(join(tmpdir(), "cursor-team-")) + try { + const config = { authInfo: { authId: "auth0|user_abc", activeTeamId: 0 } } + const seen = await run(auth1, dir, config) + const period = seen.find((r) => r.url === PERIOD) + expect(period.headers["x-cursor-team-id"]).toBeUndefined() + } finally { + await rm(dir, { recursive: true, force: true }) + } +}) + +test("no team header when cli-config.json does not exist", async () => { + const dir = await mkdtemp(join(tmpdir(), "cursor-team-")) + try { + const seen = await run(auth1, dir, undefined) // no file written + const period = seen.find((r) => r.url === PERIOD) + expect(period.headers["x-cursor-team-id"]).toBeUndefined() + } finally { + await rm(dir, { recursive: true, force: true }) + } +}) + +test("a half-written cli-config.json keeps the last team; a deleted one clears it", async () => { + const dir = await mkdtemp(join(tmpdir(), "cursor-team-")) + try { + const file = join(dir, "cli-config.json") + const header = async () => (await run(auth1, dir, undefined)).find((r) => r.url === PERIOD).headers["x-cursor-team-id"] + await writeFile(file, JSON.stringify({ authInfo: { authId: "auth0|user_abc", activeTeamId: 42 } })) + expect(await header()).toBe("42") + await writeFile(file, '{"authInfo":{"authId":"auth0|us') // cursor-agent mid-write + expect(await header()).toBe("42") + await rm(file) + expect(await header()).toBeUndefined() + } finally { + await rm(dir, { recursive: true, force: true }) + } +}) + +// A chat turn's Run is the request that meets "Team budget limit reached", +// so it carries the team too: over the native session (runNative) and, with +// no room for one, the stateless Run (runOnce). The agent API is an HTTP/2 +// server here that notes each Run's headers and answers "hi". +const { pb, frame } = _internal +const update = (num, body) => frame(pb().bytes(1, pb().bytes(num, body)).done()) +const endFrame = () => { + const f = frame(Buffer.from("{}")) + f[0] = 2 + return f +} +async function chat(a, configDir, config, { stateless = false } = {}) { + await writeFile(join(configDir, "cli-config.json"), JSON.stringify(config)) + process.env.CURSOR_CONFIG_DIR = configDir + _internal.expireTeam() + if (stateless) NATIVE_LIMITS.perProcess = 0 + const runs = [] + const server = http2.createServer() + server.on("stream", (stream, headers) => { + stream.on("error", () => {}) + runs.push(headers) + stream.respond({ ":status": 200, "content-type": "application/connect+proto" }) + let buf = Buffer.alloc(0) + stream.on("data", (c) => { + buf = Buffer.concat([buf, c]) + if (buf.length < 5 || buf.length < 5 + buf.readUInt32BE(1)) return + stream.write(update(1, pb().str(1, "hi").done())) + stream.write(update(14, pb().varint(1, 0).done())) + stream.end(endFrame()) + }) + }) + await new Promise((r) => server.listen(0, "127.0.0.1", r)) + const base = `http://127.0.0.1:${server.address().port}` + globalThis.fetch = async (url) => { + const u = String(url) + if (u.endsWith("/aiserver.v1.ServerConfigService/GetServerConfig")) return Response.json({ agentUrlConfig: { agentUrl: base } }) + if (u.endsWith("/agent.v1.AgentService/GetUsableModels")) return Response.json({ models: [{ modelId: "team-model", displayName: "Team" }] }) + if (u.endsWith("/aiserver.v1.DashboardService/GetFilteredUsageEvents")) return Response.json({ usageEventsDisplay: [] }) + throw new Error("the test asked " + u) + } + try { + const hooks = await CursorAuthPlugin() + const l = await hooks.auth.loader(async () => a) + const res = await l.fetch(base + "/v1/chat/completions", { + method: "POST", + body: JSON.stringify({ model: "team-model", messages: [{ role: "user", content: "hello" }] }), + }) + expect(res.status).toBe(200) + expect((await res.json()).choices[0].message.content).toBe("hi") + return runs + } finally { + await nativeSessions.clear() + await new Promise((r) => server.close(r)) + } +} + +for (const stateless of [false, true]) { + const path = stateless ? "stateless Run (runOnce)" : "native Run (runNative)" + + test(`a chat turn's ${path} carries the team when authId matches token`, async () => { + const dir = await mkdtemp(join(tmpdir(), "cursor-team-")) + try { + const runs = await chat(fresh("auth0|user_abc"), dir, { authInfo: { authId: "auth0|user_abc", activeTeamId: 42 } }, { stateless }) + expect(runs.length).toBeGreaterThan(0) + for (const h of runs) expect(h["x-cursor-team-id"]).toBe("42") + } finally { + await rm(dir, { recursive: true, force: true }) + } + }) + + test(`a chat turn's ${path} carries no team when authId does not match token`, async () => { + const dir = await mkdtemp(join(tmpdir(), "cursor-team-")) + try { + const runs = await chat(fresh("auth0|user_xyz"), dir, { authInfo: { authId: "auth0|user_abc", activeTeamId: 42 } }, { stateless }) + expect(runs.length).toBeGreaterThan(0) + for (const h of runs) expect(h["x-cursor-team-id"]).toBeUndefined() + } finally { + await rm(dir, { recursive: true, force: true }) + } + }) +}