Skip to content

Commit 24175f5

Browse files
lurunziTauri-EPOMivrcodex
committed
feat(rate-limits): show Cursor monthly usage in status bar
Reuse the usage service and footer for Cursor monthly allowances. Adapt paired-host preference compatibility from stablyai#20469. Co-authored-by: Tauri-EPO <[email protected]> Co-authored-by: Mihail Vratchanski <[email protected]> Co-authored-by: Codex <[email protected]> (cherry picked from commit 72d5f98)
1 parent 634ba46 commit 24175f5

55 files changed

Lines changed: 1076 additions & 132 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ Avoid type assertions except `as const`. Unavoidable casts need a line-specific
4343

4444
# Verifying Changes
4545

46+
- **Local source checks**: `pnpm ci:local` runs lint, typecheck, and unit tests using the CI commands. `pnpm ci:local --focused [test paths]` scopes lint to changed code and tests to the given paths. Packaging, rendered Electron, mobile, and other operating systems remain separate checks.
47+
4648
- **Typecheck**: `pnpm tc` (or `tc:node` / `tc:cli` / `tc:web`)
4749
- **Test**: `pnpm test [path/to/file.test.ts]`
4850
- **Lint**: `oxlint`, or `pnpm run check:code-quality:changed` for changed files (full `pnpm lint` is slow); format with `pnpm format`

‎config/scripts/ci-local.mjs‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { spawnSync } from 'node:child_process'
2+
import { resolvePnpmCliInvocation } from './pnpm-cli-invocation.mjs'
3+
4+
// Uses the same package scripts and Vitest config as pr.yml / unit-tests.yml.
5+
const invocation = resolvePnpmCliInvocation()
6+
const args = process.argv.slice(2)
7+
const focused = args[0] === '--focused'
8+
const tests = focused ? args.slice(1) : args
9+
const checks = [
10+
['run', focused ? 'check:code-quality:changed' : 'lint'],
11+
['run', 'typecheck'],
12+
['exec', 'vitest', 'run', '--config', 'config/vitest.config.ts', ...tests]
13+
]
14+
console.log(
15+
'Local source checks only; packaging, rendered Electron, mobile and other operating systems are not covered.'
16+
)
17+
if (focused) {
18+
console.log('Focused mode: changed-code lint and only the selected unit tests.')
19+
}
20+
for (const check of checks) {
21+
console.log(`pnpm ${check.join(' ')}`)
22+
const result = spawnSync(invocation.command, [...invocation.prefixArgs, ...check], {
23+
shell: invocation.shell,
24+
windowsHide: true,
25+
stdio: 'inherit',
26+
env: { ...process.env, ORCA_BACKGROUND_LAUNCH: '1' }
27+
})
28+
if (result.error || result.status !== 0) {
29+
if (result.error) {
30+
console.error(result.error.message)
31+
}
32+
process.exit(result.status ?? 1)
33+
}
34+
}

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
},
1111
"main": "./out/main/index.js",
1212
"scripts": {
13+
"ci:local": "node config/scripts/ci-local.mjs",
1314
"install:release": "pnpm install --frozen-lockfile --cpu=current,x64,arm64",
1415
"audit:perf": "oxlint --config config/oxlint-performance-audit.json --format json src",
1516
"test:perf:contracts": "vitest run --config config/vitest.performance.config.ts",

‎src/main/rate-limits/claude-oauth-usage-error.ts‎

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
// Why: a corrupt/hostile Retry-After must not gate usage refreshes for days.
2-
const MAX_RETRY_AFTER_MS = 24 * 60 * 60 * 1000
1+
import { parseRetryAfterMs } from './rate-limit-retry-after'
32

43
export class OAuthUsageError extends Error {
54
constructor(
@@ -23,23 +22,6 @@ export async function createOAuthUsageError(res: Response): Promise<OAuthUsageEr
2322
)
2423
}
2524

26-
function parseRetryAfterMs(header: string | null): number | null {
27-
if (!header) {
28-
return null
29-
}
30-
const seconds = Number(header)
31-
if (Number.isFinite(seconds)) {
32-
return seconds > 0 ? Math.min(seconds * 1000, MAX_RETRY_AFTER_MS) : null
33-
}
34-
// Why: Retry-After may also be an HTTP-date (RFC 9110).
35-
const dateMs = Date.parse(header)
36-
if (!Number.isFinite(dateMs)) {
37-
return null
38-
}
39-
const delta = dateMs - Date.now()
40-
return delta > 0 ? Math.min(delta, MAX_RETRY_AFTER_MS) : null
41-
}
42-
4325
async function describeOAuthUsageError(res: Response): Promise<string> {
4426
if (res.status === 429) {
4527
return 'Claude usage is rate limited right now.'
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
2+
import { tmpdir } from 'node:os'
3+
import { join } from 'node:path'
4+
import { afterEach, describe, expect, it } from 'vitest'
5+
import SyncDatabase from '../sqlite/sync-database'
6+
import { cursorAuthPaths, parseCursorAccessToken, readCursorAuth } from './cursor-auth'
7+
8+
const jwt = (sub = 'auth0|user_test', exp = Date.now() / 1000 + 3600): string =>
9+
`e30.${Buffer.from(JSON.stringify({ sub, exp })).toString('base64url')}.signature`
10+
const directories: string[] = []
11+
afterEach(() => {
12+
for (const directory of directories.splice(0)) {
13+
rmSync(directory, { recursive: true, force: true })
14+
}
15+
})
16+
17+
function fixture(): { cli: string; database: string } {
18+
const directory = mkdtempSync(join(tmpdir(), 'orca-cursor-auth-'))
19+
directories.push(directory)
20+
return { cli: join(directory, 'auth.json'), database: join(directory, 'state.vscdb') }
21+
}
22+
23+
describe('Cursor host credentials', () => {
24+
it('uses host-specific app and CLI paths, including spaces and absolute XDG overrides', () => {
25+
expect(cursorAuthPaths('win32', 'C:/User Name', { APPDATA: 'D:/Roaming' }).cli).toBe(
26+
'D:\\Roaming\\Cursor\\auth.json'
27+
)
28+
expect(cursorAuthPaths('darwin', '/User Name', {}).database).toBe(
29+
'/User Name/Library/Application Support/Cursor/User/globalStorage/state.vscdb'
30+
)
31+
expect(cursorAuthPaths('linux', '/home/user', { XDG_CONFIG_HOME: '/config' }).cli).toBe(
32+
'/config/cursor/auth.json'
33+
)
34+
expect(cursorAuthPaths('linux', '/home/user', { XDG_CONFIG_HOME: 'relative' }).cli).toBe(
35+
'/home/user/.config/cursor/auth.json'
36+
)
37+
})
38+
it('derives only a cookie and opaque provenance, without returning the user ID', () => {
39+
const token = jwt()
40+
const result = parseCursorAccessToken(token)
41+
expect(result.status).toBe('ok')
42+
if (result.status !== 'ok') {
43+
throw new Error('Expected valid fixture')
44+
}
45+
expect(result.cookie).toBe(`WorkosCursorSessionToken=user_test%3A%3A${token}`)
46+
expect(result.fingerprint).toMatch(/^[a-f0-9]{64}$/)
47+
})
48+
it('rejects expired, malformed and header-injection tokens', () => {
49+
expect(parseCursorAccessToken(jwt('user', 1)).status).toBe('expired')
50+
expect(parseCursorAccessToken(jwt('bad;value')).status).toBe('invalid')
51+
expect(parseCursorAccessToken('invalid\r\nCookie: leak').status).toBe('invalid')
52+
})
53+
it('keeps a present invalid CLI identity instead of falling back to the app', () => {
54+
const paths = fixture()
55+
writeFileSync(paths.cli, JSON.stringify({ accessToken: jwt('user', 1) }))
56+
expect(readCursorAuth(paths).status).toBe('expired')
57+
writeFileSync(paths.cli, '{')
58+
expect(readCursorAuth(paths).status).toBe('unreadable')
59+
})
60+
it('does not create missing credential files', () => {
61+
expect(readCursorAuth(fixture()).status).toBe('missing')
62+
})
63+
it.each(['text', 'utf8', 'utf16le'] as const)(
64+
'reads %s app tokens with a read-only SQLite connection',
65+
(encoding) => {
66+
const paths = fixture()
67+
const db = new SyncDatabase(paths.database)
68+
const token = jwt()
69+
db.exec('CREATE TABLE ItemTable (key TEXT PRIMARY KEY, value BLOB)')
70+
db.prepare('INSERT INTO ItemTable VALUES (?, ?)').run(
71+
'cursorAuth/accessToken',
72+
encoding === 'text' ? token : Buffer.from(token, encoding)
73+
)
74+
db.close()
75+
expect(readCursorAuth(paths)).toEqual(parseCursorAccessToken(token))
76+
}
77+
)
78+
})
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import { createHash } from 'node:crypto'
2+
import { existsSync, readFileSync } from 'node:fs'
3+
import { homedir } from 'node:os'
4+
import path from 'node:path'
5+
import { z } from 'zod'
6+
import SyncDatabase from '../sqlite/sync-database'
7+
8+
export type CursorAuth =
9+
| { status: 'ok'; cookie: string; fingerprint: string }
10+
| { status: 'missing' | 'expired' | 'invalid' | 'unreadable' }
11+
12+
export function cursorAuthPaths(
13+
platform = process.platform,
14+
home = homedir(),
15+
env = process.env
16+
): { cli: string; database: string } {
17+
const paths = platform === 'win32' ? path.win32 : path.posix
18+
const absolute = (value: string | undefined): string | undefined =>
19+
value && paths.isAbsolute(value) ? value : undefined
20+
const config =
21+
platform === 'win32'
22+
? (absolute(env.APPDATA) ?? paths.join(home, 'AppData', 'Roaming'))
23+
: platform === 'darwin'
24+
? paths.join(home, 'Library', 'Application Support')
25+
: (absolute(env.XDG_CONFIG_HOME) ?? paths.join(home, '.config'))
26+
return {
27+
cli:
28+
platform === 'darwin'
29+
? paths.join(home, '.cursor', 'auth.json')
30+
: paths.join(config, platform === 'win32' ? 'Cursor' : 'cursor', 'auth.json'),
31+
database: paths.join(config, 'Cursor', 'User', 'globalStorage', 'state.vscdb')
32+
}
33+
}
34+
35+
const jwtPayload = z.object({ sub: z.string(), exp: z.number().finite() })
36+
37+
// Protocol reference: steipete/CodexBar (MIT), CursorAppAuth.swift; credentials stay on the host.
38+
export function parseCursorAccessToken(token: unknown, now = Date.now()): CursorAuth {
39+
if (typeof token !== 'string' || !token) {
40+
return { status: 'missing' }
41+
}
42+
if (!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token)) {
43+
return { status: 'invalid' }
44+
}
45+
try {
46+
const payload = jwtPayload.parse(
47+
JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString())
48+
)
49+
const userId = payload.sub.split('|').at(-1)
50+
if (!userId || !/^[A-Za-z0-9._-]+$/.test(userId)) {
51+
return { status: 'invalid' }
52+
}
53+
if (payload.exp * 1000 <= now + 60_000) {
54+
return { status: 'expired' }
55+
}
56+
return {
57+
status: 'ok',
58+
cookie: `WorkosCursorSessionToken=${encodeURIComponent(`${userId}::${token}`)}`,
59+
fingerprint: createHash('sha256').update(token).digest('hex')
60+
}
61+
} catch {
62+
return { status: 'invalid' }
63+
}
64+
}
65+
66+
function decodeToken(value: unknown): unknown {
67+
if (!(value instanceof Uint8Array)) {
68+
return value
69+
}
70+
const bytes = Buffer.from(value)
71+
return bytes.toString(bytes.length % 2 === 0 && bytes[1] === 0 ? 'utf16le' : 'utf8')
72+
}
73+
74+
export function readCursorAuth(paths = cursorAuthPaths()): CursorAuth {
75+
try {
76+
// A present CLI identity wins, even when expired, to avoid silently switching accounts.
77+
if (existsSync(paths.cli)) {
78+
const parsed = z
79+
.object({ accessToken: z.string().optional() })
80+
.safeParse(JSON.parse(readFileSync(paths.cli, 'utf8')))
81+
return parsed.success
82+
? parseCursorAccessToken(parsed.data.accessToken)
83+
: { status: 'invalid' }
84+
}
85+
if (!existsSync(paths.database)) {
86+
return { status: 'missing' }
87+
}
88+
const db = new SyncDatabase(paths.database, {
89+
readonly: true,
90+
fileMustExist: true,
91+
timeout: 250
92+
})
93+
try {
94+
const row = db
95+
.prepare('SELECT value FROM ItemTable WHERE key = ? LIMIT 1')
96+
.get('cursorAuth/accessToken')
97+
return parseCursorAccessToken(decodeToken(row?.value))
98+
} finally {
99+
db.close()
100+
}
101+
} catch {
102+
return { status: 'unreadable' }
103+
}
104+
}
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import { beforeEach, describe, expect, it, vi } from 'vitest'
2+
import { net } from 'electron'
3+
import { readCursorAuth } from './cursor-auth'
4+
import { fetchCursorRateLimits } from './cursor-fetcher'
5+
6+
vi.mock('electron', () => ({ net: { fetch: vi.fn() } }))
7+
vi.mock('./cursor-auth', () => ({ readCursorAuth: vi.fn() }))
8+
const auth = {
9+
status: 'ok',
10+
cookie: 'WorkosCursorSessionToken=synthetic',
11+
fingerprint: 'account-a'
12+
} as const
13+
beforeEach(() => {
14+
vi.resetAllMocks()
15+
vi.mocked(readCursorAuth).mockReturnValue(auth)
16+
})
17+
18+
describe('Cursor usage request', () => {
19+
it('reads the dashboard with bounded cancellation and never publishes the credential', async () => {
20+
vi.mocked(net.fetch).mockResolvedValue(
21+
new Response(JSON.stringify({ individualUsage: { plan: { totalPercentUsed: 35 } } }))
22+
)
23+
const result = await fetchCursorRateLimits()
24+
expect(result.monthly?.usedPercent).toBe(35)
25+
expect(result.session).toBeNull()
26+
expect(JSON.stringify(result)).not.toContain(auth.cookie)
27+
expect(net.fetch).toHaveBeenCalledWith(
28+
'https://cursor.com/api/usage-summary',
29+
expect.objectContaining({
30+
redirect: 'error',
31+
signal: expect.any(AbortSignal),
32+
headers: { Cookie: auth.cookie, Accept: 'application/json' }
33+
})
34+
)
35+
})
36+
it('makes no network request without credentials', async () => {
37+
vi.mocked(readCursorAuth).mockReturnValue({ status: 'missing' })
38+
expect((await fetchCursorRateLimits()).status).toBe('unavailable')
39+
expect(net.fetch).not.toHaveBeenCalled()
40+
})
41+
it.each([
42+
[401, 'stale-token'],
43+
[403, 'stale-token'],
44+
[429, 'rate-limited'],
45+
[500, 'server']
46+
])('classifies HTTP %s without leaking the response', async (status, kind) => {
47+
vi.mocked(net.fetch).mockResolvedValue(
48+
new Response('secret response', { status: Number(status) })
49+
)
50+
const result = await fetchCursorRateLimits()
51+
expect(result.usageMetadata?.failureKind).toBe(kind)
52+
expect(JSON.stringify(result)).not.toContain('secret response')
53+
})
54+
it('does not interpret an unknown payload as unused quota', async () => {
55+
vi.mocked(net.fetch).mockResolvedValue(new Response('{}'))
56+
expect((await fetchCursorRateLimits()).usageMetadata?.failureKind).toBe('usage-unavailable')
57+
})
58+
it('drops an in-flight result when the account changes', async () => {
59+
vi.mocked(net.fetch).mockResolvedValue(
60+
new Response(JSON.stringify({ individualUsage: { plan: { totalPercentUsed: 35 } } }))
61+
)
62+
vi.mocked(readCursorAuth)
63+
.mockReturnValueOnce(auth)
64+
.mockReturnValueOnce({ ...auth, fingerprint: 'account-b' })
65+
const result = await fetchCursorRateLimits()
66+
expect(result.status).toBe('error')
67+
expect(result.monthly).toBeNull()
68+
expect(result.usageMetadata?.authProvenance).toBeUndefined()
69+
})
70+
it('redacts exceptions and forwards caller cancellation', async () => {
71+
vi.mocked(net.fetch).mockRejectedValue(new Error(auth.cookie))
72+
const controller = new AbortController()
73+
controller.abort()
74+
const result = await fetchCursorRateLimits({ signal: controller.signal })
75+
expect(result.error).not.toContain(auth.cookie)
76+
expect(vi.mocked(net.fetch).mock.calls[0][1]?.signal?.aborted).toBe(true)
77+
})
78+
it('honors Retry-After even for manual refreshes and releases it after account changes', async () => {
79+
vi.mocked(net.fetch).mockResolvedValue(
80+
new Response('', { status: 429, headers: { 'retry-after': '600' } })
81+
)
82+
const first = await fetchCursorRateLimits()
83+
expect(first.usageMetadata?.retryAtMs).toBeGreaterThan(Date.now())
84+
const deferred = await fetchCursorRateLimits({ previous: first })
85+
expect(deferred).toEqual(first)
86+
expect(net.fetch).toHaveBeenCalledTimes(1)
87+
vi.mocked(readCursorAuth).mockReturnValue({ ...auth, fingerprint: 'account-b' })
88+
await fetchCursorRateLimits({ previous: first })
89+
expect(net.fetch).toHaveBeenCalledTimes(2)
90+
})
91+
})

0 commit comments

Comments
 (0)