@rahularya01/pi-cursor 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/README.md +174 -0
- package/package.json +67 -0
- package/src/auth/cli-credentials.ts +168 -0
- package/src/auth/index.ts +10 -0
- package/src/auth/oauth.ts +214 -0
- package/src/client/bridge.ts +206 -0
- package/src/client/cursor-wire.ts +212 -0
- package/src/client/h2-bridge.mjs +208 -0
- package/src/client/index.ts +19 -0
- package/src/diagnostics/diagnostics.ts +62 -0
- package/src/diagnostics/index.ts +1 -0
- package/src/index.ts +1393 -0
- package/src/models/catalog.json +1163 -0
- package/src/models/index.ts +2 -0
- package/src/proto/agent_pb.ts +15294 -0
- package/src/stream/index.ts +11 -0
- package/src/stream/native-core.ts +5760 -0
- package/src/usage.ts +262 -0
- package/src/utils/index.ts +2 -0
- package/src/utils/security.ts +65 -0
- package/src/utils/util.ts +19 -0
- package/tsconfig.json +21 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [1.0.0] - 2026-07-23
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- Initial stable release of `@rahularya01/pi-cursor` provider for Pi Coding Agent.
|
|
8
|
+
- 4-tier authentication resolution cascade: automatically resolves tokens from `CURSOR_ACCESS_TOKEN` env var, macOS Keychain (Cursor CLI), Cursor IDE local state (`state.vscdb`), and Pi OAuth store (`~/.pi/agent/auth.json`).
|
|
9
|
+
- Automatic WSL (Windows Subsystem for Linux) host Windows AppData credential auto-discovery.
|
|
10
|
+
- Deep-link PKCE browser OAuth (`/login cursor`) with token refresh.
|
|
11
|
+
- Native `streamSimple` transport over Connect/protobuf HTTP/2 via `h2-bridge.mjs`.
|
|
12
|
+
- Live model discovery (`GetUsableModels` + parameterized metadata) with static fallback catalog.
|
|
13
|
+
- Effort-suffix model collapse and Pi thinking-level routing.
|
|
14
|
+
- Context-mode normalization: side-channel user messages (such as context-mode routing or post-compaction `<session_state>` blocks) are safely normalized into the system prompt so Cursor models stay focused on the user's task.
|
|
15
|
+
- Visual TUI usage dashboard (`/cursor.usage`) with progress bars, plan breakdown (`Included`, `Auto`, `API`), reset dates, and dashboard link.
|
|
16
|
+
- Sanitized provider diagnostics command (`/cursor.doctor`) and model catalog command (`/cursor.models`).
|
|
17
|
+
- GitHub Actions CI/CD workflows targeting Node 22 and 24 for automated testing and npm publishing.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Rahul Arya
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
# @rahularya01/pi-cursor
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@rahularya01/pi-cursor)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
|
|
6
|
+
A Pi Coding Agent provider for **Cursor** models. It adds provider `cursor`, multi-source authentication resolution (macOS Keychain, Cursor IDE, WSL host, environment variables, or PKCE browser OAuth), native Connect/protobuf streaming over HTTP/2, model discovery, thinking effort routing, and visual TUI usage diagnostics—without invoking the Cursor CLI for day-to-day chat.
|
|
7
|
+
|
|
8
|
+
> **Unofficial integration.** This project is not affiliated with or endorsed by Cursor / Anysphere. It uses reverse-engineered Wire protocol details shared by community clients (see attributions). Use it only with an account you are authorized to access, and review its source before granting OAuth permissions. Cursor may change wire protocol endpoints or formats at any time.
|
|
9
|
+
|
|
10
|
+
## Requirements
|
|
11
|
+
|
|
12
|
+
- Pi Coding Agent and Pi AI version **0.80.0 or later**
|
|
13
|
+
- A Cursor account with model access (or Cursor CLI / Cursor IDE logged in on your machine)
|
|
14
|
+
- Node.js version **22.0.0 or later** (for native HTTP/2 Connect streaming and SQLite credential resolution)
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
Install from npm:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pi install npm:@rahularya01/pi-cursor
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Or install the latest repository version:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pi install git:github.com/Rahularya01/pi-cursor
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Restart Pi (or run `/reload`) after installation. To update the package later, run `pi update npm:@rahularya01/pi-cursor`.
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
33
|
+
|
|
34
|
+
1. If you are already logged in to Cursor CLI or the Cursor app on your machine, `pi-cursor` auto-detects your credentials. Otherwise, start Pi and run `/login cursor` to sign in via browser.
|
|
35
|
+
2. Select a model, for example:
|
|
36
|
+
|
|
37
|
+
```text
|
|
38
|
+
/model cursor/composer-2
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
3. Start working. Use `/cursor.doctor` to verify diagnostics and active authentication source.
|
|
42
|
+
|
|
43
|
+
## Authentication and resolution cascade
|
|
44
|
+
|
|
45
|
+
`pi-cursor` automatically resolves credentials using a 4-tier cascade:
|
|
46
|
+
|
|
47
|
+
```text
|
|
48
|
+
1. CURSOR_ACCESS_TOKEN environment variable
|
|
49
|
+
2. Cursor CLI credentials in macOS Keychain (cursor-access-token / cursor-refresh-token)
|
|
50
|
+
3. Cursor IDE local state DB (globalStorage/state.vscdb on macOS, Windows, Linux, or WSL)
|
|
51
|
+
4. Pi OAuth credentials store (~/.pi/agent/auth.json via /login cursor)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### Automatic CLI & IDE login detection
|
|
55
|
+
|
|
56
|
+
If you are logged into the Cursor desktop app or Cursor CLI (`cursor` / `agent`), `pi-cursor` automatically extracts your session credentials so you can start chatting immediately without manual browser login.
|
|
57
|
+
|
|
58
|
+
On **WSL (Windows Subsystem for Linux)**, `pi-cursor` automatically scans Windows host user profiles (`/mnt/c/Users/*/AppData/...`) to detect and reuse your Windows Cursor app login.
|
|
59
|
+
|
|
60
|
+
### Deep-link PKCE browser login
|
|
61
|
+
|
|
62
|
+
When no local credentials exist, running `/login cursor` initiates browser sign-in:
|
|
63
|
+
|
|
64
|
+
1. `/login cursor` opens `https://cursor.com/loginDeepControl?...`
|
|
65
|
+
2. Pi polls `https://api2.cursor.sh/auth/poll` until authentication completes.
|
|
66
|
+
3. Access and refresh tokens are stored in Pi's auth store (`~/.pi/agent/auth.json`).
|
|
67
|
+
4. Tokens are automatically refreshed via `https://api2.cursor.sh/auth/exchange_user_api_key`.
|
|
68
|
+
|
|
69
|
+
Use `/cursor.doctor` to inspect which source is active (`tokenSource=cli_keychain`, `tokenSource=ide_vscdb`, `tokenSource=pi_oauth`, `tokenSource=env`).
|
|
70
|
+
|
|
71
|
+
## Commands
|
|
72
|
+
|
|
73
|
+
| Command | Description |
|
|
74
|
+
| -------------------- | ------------------------------------------------------------------------------------------------ |
|
|
75
|
+
| `/login cursor` | Sign in to Cursor via browser PKCE and refresh the live model catalog. |
|
|
76
|
+
| `/model cursor/<id>` | Choose a registered Cursor model. |
|
|
77
|
+
| `/cursor.models` | List active runtime models, context windows, and effort capabilities. |
|
|
78
|
+
| `/cursor.models all` | Include tab/chat internal model variants normally hidden from the picker. |
|
|
79
|
+
| `/cursor.usage` | Display visual TUI usage dashboard (included/auto/API quota bars, reset dates, on-demand spend). |
|
|
80
|
+
| `/cursor.doctor` | Show sanitized provider diagnostics, active token source, endpoint, and last error. |
|
|
81
|
+
|
|
82
|
+
## Models and reasoning effort routing
|
|
83
|
+
|
|
84
|
+
`pi-cursor` discovers live account models via `GetUsableModels` and parameterized metadata. Reasoning effort levels (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`) are mapped directly to Cursor's runtime model variants or reasoning parameters.
|
|
85
|
+
|
|
86
|
+
| Public model ID | Context | Thinking | Description / Routing |
|
|
87
|
+
| ------------------------ | ------- | -------- | ---------------------------------------------------------- |
|
|
88
|
+
| `cursor/composer-2` | 200,000 | Yes | Cursor's agentic model with fast reasoning effort options. |
|
|
89
|
+
| `cursor/composer-1.5` | 200,000 | Yes | Fast agent model optimized for code edit turns. |
|
|
90
|
+
| `cursor/claude-sonnet-5` | 200,000 | Yes | Anthropic Claude Sonnet via Cursor infrastructure. |
|
|
91
|
+
| `cursor/gpt-5.5` | 200,000 | Yes | OpenAI flagship model with parameterized reasoning levels. |
|
|
92
|
+
| `cursor/grok-4.5` | 200,000 | Yes | xAI Grok model via Cursor infrastructure. |
|
|
93
|
+
|
|
94
|
+
To restrict which models Pi displays, configure `~/.pi/agent/settings.json`:
|
|
95
|
+
|
|
96
|
+
```json
|
|
97
|
+
{
|
|
98
|
+
"enabledModels": ["cursor/composer-2", "cursor/claude-sonnet-5", "cursor/gpt-5.5"]
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Usage quota and visual TUI dashboard
|
|
103
|
+
|
|
104
|
+
Running `/cursor.usage` displays a formatted terminal interface showing your current billing cycle, progress bars for included plan quota, auto/API usage, reset dates, and on-demand spend:
|
|
105
|
+
|
|
106
|
+
```text
|
|
107
|
+
Usage • Pro Resets 5 Aug
|
|
108
|
+
Monthly plan and on-demand usage
|
|
109
|
+
|
|
110
|
+
Category Current Usage
|
|
111
|
+
Included 13% used ███░░░░░░░░░░░░░░░░░
|
|
112
|
+
Auto 12% used ███░░░░░░░░░░░░░░░░░
|
|
113
|
+
API 14% used ███░░░░░░░░░░░░░░░░░
|
|
114
|
+
On-Demand Disabled
|
|
115
|
+
------------------------------------------------------------
|
|
116
|
+
On-demand usage is off
|
|
117
|
+
|
|
118
|
+
View in dashboard: cursor.com/dashboard?tab=usage
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Usage statistics are fetched directly from Cursor's native Connect period usage endpoint (`POST https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage`) using your active access token, with optional fallback to `CURSOR_USAGE_SESSION_TOKEN`.
|
|
122
|
+
|
|
123
|
+
## Architecture & Wire Protocol
|
|
124
|
+
|
|
125
|
+
```text
|
|
126
|
+
Pi Coding Agent → streamSimple (cursor-native)
|
|
127
|
+
→ h2-bridge.mjs (Node.js HTTP/2 child process)
|
|
128
|
+
→ agent.v1.AgentService/Run (Connect + Protobuf over HTTP/2)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
- **Transport:** Native Connect/protobuf streaming over HTTP/2 via `h2-bridge.mjs`.
|
|
132
|
+
- **Context-Mode Normalization:** Side-channel user messages (such as context-mode routing or post-compaction `<session_state>` blocks) are safely normalized into the system prompt so Cursor models stay focused on your primary task.
|
|
133
|
+
- **Cross-Platform:** Tested and fully compatible with macOS, Linux, Windows, and WSL.
|
|
134
|
+
|
|
135
|
+
## Configuration
|
|
136
|
+
|
|
137
|
+
| Variable | Purpose |
|
|
138
|
+
| ------------------------------------------ | ------------------------------------------------------------------------ |
|
|
139
|
+
| `PI_CURSOR_AGENT_URL` / `CURSOR_AGENT_URL` | Override agent base URL (default: `https://agentn.us.api5.cursor.sh`). |
|
|
140
|
+
| `CURSOR_ACCESS_TOKEN` | Static access token override. |
|
|
141
|
+
| `PI_CURSOR_CLIENT_VERSION` | Pin `x-cursor-client-version` header sent by the HTTP/2 bridge. |
|
|
142
|
+
| `PI_CURSOR_RAW_MODELS` | Disable effort-suffix model collapse. |
|
|
143
|
+
| `PI_CURSOR_PROVIDER_DEBUG` | Enable JSONL debug logging (`/tmp/pi-cursor-debug.jsonl`). |
|
|
144
|
+
| `CURSOR_USAGE_SESSION_TOKEN` | Optional `WorkosCursorSessionToken` fallback cookie for `/cursor.usage`. |
|
|
145
|
+
| `PI_OFFLINE` | Skip live model discovery on startup. |
|
|
146
|
+
|
|
147
|
+
## Troubleshooting
|
|
148
|
+
|
|
149
|
+
- **Not logged in / 401:** Ensure Cursor CLI or app is logged in, or run `/login cursor` again. Check `/cursor.doctor` to verify your `tokenSource`.
|
|
150
|
+
- **Empty / hung stream:** Cursor may have updated wire headers; verify network connectivity or bump `PI_CURSOR_CLIENT_VERSION`.
|
|
151
|
+
- **Tool continuation lost:** Retry the turn or start a new chat (the live upstream HTTP/2 stream was interrupted mid-tool).
|
|
152
|
+
- **WSL credential detection:** Ensure your Windows user profile folder exists under `/mnt/c/Users/` and is readable from WSL.
|
|
153
|
+
|
|
154
|
+
## Development
|
|
155
|
+
|
|
156
|
+
```bash
|
|
157
|
+
npm install
|
|
158
|
+
npm run check
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
`npm run check` runs TypeScript typechecking, ESLint, Prettier format verification, security checks, and unit tests.
|
|
162
|
+
|
|
163
|
+
## Attributions
|
|
164
|
+
|
|
165
|
+
Wire protocol and authentication patterns adapted from MIT community client lineage:
|
|
166
|
+
|
|
167
|
+
- [ephraimduncan/opencode-cursor](https://github.com/ephraimduncan/opencode-cursor)
|
|
168
|
+
- [@pi-stef/cursor](https://www.npmjs.com/package/@pi-stef/cursor)
|
|
169
|
+
|
|
170
|
+
Package structure mirrors [pi-antigravity](https://github.com/Rahularya01/pi-antigravity).
|
|
171
|
+
|
|
172
|
+
## License
|
|
173
|
+
|
|
174
|
+
[MIT](LICENSE)
|
package/package.json
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rahularya01/pi-cursor",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Native Cursor provider for Pi Coding Agent (OAuth + Connect/protobuf streamSimple)",
|
|
5
|
+
"author": "Rahul Arya",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/Rahularya01/pi-cursor.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/Rahularya01/pi-cursor#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/Rahularya01/pi-cursor/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"main": "./src/index.ts",
|
|
17
|
+
"keywords": [
|
|
18
|
+
"pi-package",
|
|
19
|
+
"pi-extension",
|
|
20
|
+
"cursor",
|
|
21
|
+
"oauth",
|
|
22
|
+
"provider"
|
|
23
|
+
],
|
|
24
|
+
"files": [
|
|
25
|
+
"LICENSE",
|
|
26
|
+
"README.md",
|
|
27
|
+
"CHANGELOG.md",
|
|
28
|
+
"src",
|
|
29
|
+
"tsconfig.json"
|
|
30
|
+
],
|
|
31
|
+
"scripts": {
|
|
32
|
+
"typecheck": "tsc --noEmit",
|
|
33
|
+
"lint": "eslint src",
|
|
34
|
+
"lint:fix": "eslint src --fix",
|
|
35
|
+
"format": "prettier --write .",
|
|
36
|
+
"format:check": "prettier --check .",
|
|
37
|
+
"security-check": "tsx scripts/security-check.ts",
|
|
38
|
+
"test": "tsx scripts/test-model-routing.ts && tsx scripts/test-thinking-levels.ts && tsx scripts/test-usage.ts && tsx scripts/test-context-mode-normalize.ts && tsx scripts/test-cli-auth.ts",
|
|
39
|
+
"smoke:auth": "node --import tsx scripts/smoke-auth.mjs",
|
|
40
|
+
"smoke:models": "node --import tsx scripts/smoke-models.mjs",
|
|
41
|
+
"smoke:stream": "node --import tsx scripts/smoke-stream.mjs",
|
|
42
|
+
"check": "npm run typecheck && npm run lint && npm run format:check && npm run security-check && npm test"
|
|
43
|
+
},
|
|
44
|
+
"pi": {
|
|
45
|
+
"extensions": [
|
|
46
|
+
"./src/index.ts"
|
|
47
|
+
]
|
|
48
|
+
},
|
|
49
|
+
"dependencies": {
|
|
50
|
+
"@bufbuild/protobuf": "^2.0.0"
|
|
51
|
+
},
|
|
52
|
+
"peerDependencies": {
|
|
53
|
+
"@earendil-works/pi-ai": ">=0.80.0",
|
|
54
|
+
"@earendil-works/pi-coding-agent": ">=0.80.0"
|
|
55
|
+
},
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@eslint/js": "^10.0.1",
|
|
58
|
+
"@types/node": "^26.1.1",
|
|
59
|
+
"eslint": "^10.7.0",
|
|
60
|
+
"eslint-config-prettier": "^10.1.8",
|
|
61
|
+
"globals": "^17.7.0",
|
|
62
|
+
"prettier": "^3.9.5",
|
|
63
|
+
"tsx": "^4.23.1",
|
|
64
|
+
"typescript": "^6.0.3",
|
|
65
|
+
"typescript-eslint": "^8.64.0"
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { existsSync, readdirSync } from "node:fs";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { homedir, platform } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { getCursorAccessTokenFromEnv, getTokenExpiry, refreshCursorToken } from "./oauth.js";
|
|
6
|
+
|
|
7
|
+
export type CredentialSource =
|
|
8
|
+
| "env"
|
|
9
|
+
| "cli_keychain"
|
|
10
|
+
| "cli_keychain_refresh"
|
|
11
|
+
| "ide_vscdb"
|
|
12
|
+
| "ide_vscdb_refresh"
|
|
13
|
+
| "pi_oauth"
|
|
14
|
+
| "pi_oauth_refresh";
|
|
15
|
+
|
|
16
|
+
export interface CursorTokenResult {
|
|
17
|
+
accessToken: string;
|
|
18
|
+
source: CredentialSource;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Reads token from macOS Keychain (security CLI).
|
|
23
|
+
*/
|
|
24
|
+
export async function getCursorKeychainToken(): Promise<CursorTokenResult | undefined> {
|
|
25
|
+
if (platform() !== "darwin") return undefined;
|
|
26
|
+
|
|
27
|
+
let accessToken: string | undefined;
|
|
28
|
+
let refreshToken: string | undefined;
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
const rawAccess = execFileSync(
|
|
32
|
+
"security",
|
|
33
|
+
["find-generic-password", "-s", "cursor-access-token", "-a", "cursor-user", "-w"],
|
|
34
|
+
{ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000 },
|
|
35
|
+
).trim();
|
|
36
|
+
if (rawAccess) accessToken = rawAccess;
|
|
37
|
+
} catch {
|
|
38
|
+
// Keychain item not found or error
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
try {
|
|
42
|
+
const rawRefresh = execFileSync(
|
|
43
|
+
"security",
|
|
44
|
+
["find-generic-password", "-s", "cursor-refresh-token", "-a", "cursor-user", "-w"],
|
|
45
|
+
{ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000 },
|
|
46
|
+
).trim();
|
|
47
|
+
if (rawRefresh) refreshToken = rawRefresh;
|
|
48
|
+
} catch {
|
|
49
|
+
// Keychain item not found or error
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (accessToken && Date.now() < getTokenExpiry(accessToken)) {
|
|
53
|
+
return { accessToken, source: "cli_keychain" };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (refreshToken) {
|
|
57
|
+
try {
|
|
58
|
+
const refreshed = await refreshCursorToken(refreshToken);
|
|
59
|
+
return { accessToken: refreshed.access, source: "cli_keychain_refresh" };
|
|
60
|
+
} catch {
|
|
61
|
+
// Refresh failed
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function getDatabaseSync() {
|
|
69
|
+
try {
|
|
70
|
+
const mod = await import("node:sqlite");
|
|
71
|
+
return mod.DatabaseSync;
|
|
72
|
+
} catch {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Reads token from Cursor IDE state.vscdb.
|
|
79
|
+
*/
|
|
80
|
+
export async function getCursorVscdbToken(): Promise<CursorTokenResult | undefined> {
|
|
81
|
+
const DatabaseSyncClass = await getDatabaseSync();
|
|
82
|
+
if (!DatabaseSyncClass) return undefined;
|
|
83
|
+
|
|
84
|
+
const dbPaths: string[] = [];
|
|
85
|
+
const home = homedir();
|
|
86
|
+
|
|
87
|
+
if (platform() === "darwin") {
|
|
88
|
+
dbPaths.push(join(home, "Library/Application Support/Cursor/User/globalStorage/state.vscdb"));
|
|
89
|
+
} else if (platform() === "win32") {
|
|
90
|
+
if (process.env.APPDATA) {
|
|
91
|
+
dbPaths.push(join(process.env.APPDATA, "Cursor/User/globalStorage/state.vscdb"));
|
|
92
|
+
}
|
|
93
|
+
} else {
|
|
94
|
+
// Linux / WSL
|
|
95
|
+
dbPaths.push(join(home, ".config/Cursor/User/globalStorage/state.vscdb"));
|
|
96
|
+
// If running inside WSL, auto-detect Windows host Cursor credentials
|
|
97
|
+
if (process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP || existsSync("/mnt/c/Users")) {
|
|
98
|
+
try {
|
|
99
|
+
const usersDir = "/mnt/c/Users";
|
|
100
|
+
if (existsSync(usersDir)) {
|
|
101
|
+
for (const user of readdirSync(usersDir)) {
|
|
102
|
+
if (user === "Public" || user === "Default" || user.startsWith(".")) continue;
|
|
103
|
+
dbPaths.push(
|
|
104
|
+
join(usersDir, user, "AppData/Roaming/Cursor/User/globalStorage/state.vscdb"),
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
} catch {
|
|
109
|
+
// Ignore read permission errors on Windows user profiles
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
for (const dbPath of dbPaths) {
|
|
115
|
+
try {
|
|
116
|
+
const db = new DatabaseSyncClass(dbPath, { readOnly: true });
|
|
117
|
+
|
|
118
|
+
const accessRow = db
|
|
119
|
+
.prepare("SELECT value FROM ItemTable WHERE key = 'cursorAuth/accessToken'")
|
|
120
|
+
.get() as { value?: string } | undefined;
|
|
121
|
+
const refreshRow = db
|
|
122
|
+
.prepare("SELECT value FROM ItemTable WHERE key = 'cursorAuth/refreshToken'")
|
|
123
|
+
.get() as { value?: string } | undefined;
|
|
124
|
+
|
|
125
|
+
db.close();
|
|
126
|
+
|
|
127
|
+
const accessToken = typeof accessRow?.value === "string" ? accessRow.value.trim() : undefined;
|
|
128
|
+
const refreshToken =
|
|
129
|
+
typeof refreshRow?.value === "string" ? refreshRow.value.trim() : undefined;
|
|
130
|
+
|
|
131
|
+
if (accessToken && Date.now() < getTokenExpiry(accessToken)) {
|
|
132
|
+
return { accessToken, source: "ide_vscdb" };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (refreshToken) {
|
|
136
|
+
try {
|
|
137
|
+
const refreshed = await refreshCursorToken(refreshToken);
|
|
138
|
+
return { accessToken: refreshed.access, source: "ide_vscdb_refresh" };
|
|
139
|
+
} catch {
|
|
140
|
+
// Refresh failed
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
} catch {
|
|
144
|
+
// Database missing or unreadable
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Full credential resolution cascade:
|
|
153
|
+
* 1. CURSOR_ACCESS_TOKEN env var
|
|
154
|
+
* 2. macOS Keychain (Cursor CLI)
|
|
155
|
+
* 3. Cursor IDE state.vscdb
|
|
156
|
+
*/
|
|
157
|
+
export async function resolveSystemCursorAccessToken(): Promise<CursorTokenResult | undefined> {
|
|
158
|
+
const envToken = getCursorAccessTokenFromEnv();
|
|
159
|
+
if (envToken) return { accessToken: envToken, source: "env" };
|
|
160
|
+
|
|
161
|
+
const keychainToken = await getCursorKeychainToken();
|
|
162
|
+
if (keychainToken) return keychainToken;
|
|
163
|
+
|
|
164
|
+
const vscdbToken = await getCursorVscdbToken();
|
|
165
|
+
if (vscdbToken) return vscdbToken;
|
|
166
|
+
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cursor OAuth authentication via PKCE.
|
|
3
|
+
*
|
|
4
|
+
* Flow:
|
|
5
|
+
* 1. Generate PKCE verifier + challenge
|
|
6
|
+
* 2. Open browser to cursor.com/loginDeepControl
|
|
7
|
+
* 3. Poll api2.cursor.sh/auth/poll until tokens arrive
|
|
8
|
+
* 4. Refresh via api2.cursor.sh/auth/exchange_user_api_key
|
|
9
|
+
*
|
|
10
|
+
* Based on https://github.com/ephraimduncan/opencode-cursor by Ephraim Duncan.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const CURSOR_LOGIN_URL = "https://cursor.com/loginDeepControl";
|
|
14
|
+
const CURSOR_POLL_URL = "https://api2.cursor.sh/auth/poll";
|
|
15
|
+
const CURSOR_REFRESH_URL = "https://api2.cursor.sh/auth/exchange_user_api_key";
|
|
16
|
+
const POLL_MAX_ATTEMPTS = 150;
|
|
17
|
+
const POLL_BASE_DELAY = 1000;
|
|
18
|
+
const POLL_MAX_DELAY = 10_000;
|
|
19
|
+
const POLL_BACKOFF_MULTIPLIER = 1.2;
|
|
20
|
+
|
|
21
|
+
// ── PKCE ──
|
|
22
|
+
|
|
23
|
+
async function generatePKCE(): Promise<{ verifier: string; challenge: string }> {
|
|
24
|
+
const verifierBytes = new Uint8Array(96);
|
|
25
|
+
crypto.getRandomValues(verifierBytes);
|
|
26
|
+
const verifier = Buffer.from(verifierBytes).toString("base64url");
|
|
27
|
+
|
|
28
|
+
const data = new TextEncoder().encode(verifier);
|
|
29
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
30
|
+
const challenge = Buffer.from(hashBuffer).toString("base64url");
|
|
31
|
+
|
|
32
|
+
return { verifier, challenge };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// ── Login params ──
|
|
36
|
+
|
|
37
|
+
export interface CursorAuthParams {
|
|
38
|
+
verifier: string;
|
|
39
|
+
challenge: string;
|
|
40
|
+
uuid: string;
|
|
41
|
+
loginUrl: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface CursorAuthClientDependencies {
|
|
45
|
+
fetch?: typeof fetch;
|
|
46
|
+
generatePkce?: () => Promise<{ verifier: string; challenge: string; uuid?: string }>;
|
|
47
|
+
randomUUID?: () => string;
|
|
48
|
+
sleep?: (ms: number) => Promise<void>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface CursorAuthLoginCallbacks {
|
|
52
|
+
onAuth(payload: { url: string }): void | Promise<void>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function createCursorAuthClient(deps: CursorAuthClientDependencies = {}) {
|
|
56
|
+
const fetchImpl = deps.fetch ?? fetch;
|
|
57
|
+
const sleepImpl =
|
|
58
|
+
deps.sleep ??
|
|
59
|
+
((ms: number) =>
|
|
60
|
+
new Promise<void>((resolve) => {
|
|
61
|
+
setTimeout(resolve, ms);
|
|
62
|
+
}));
|
|
63
|
+
const generatePkceImpl: () => Promise<{ verifier: string; challenge: string; uuid?: string }> =
|
|
64
|
+
deps.generatePkce ?? generatePKCE;
|
|
65
|
+
const randomUUIDImpl = deps.randomUUID ?? (() => crypto.randomUUID());
|
|
66
|
+
|
|
67
|
+
async function generateParams(): Promise<CursorAuthParams> {
|
|
68
|
+
const { verifier, challenge, uuid: injectedUuid } = await generatePkceImpl();
|
|
69
|
+
const uuid = injectedUuid ?? randomUUIDImpl();
|
|
70
|
+
|
|
71
|
+
const params = new URLSearchParams({
|
|
72
|
+
challenge,
|
|
73
|
+
uuid,
|
|
74
|
+
mode: "login",
|
|
75
|
+
redirectTarget: "cli",
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
const loginUrl = `${CURSOR_LOGIN_URL}?${params.toString()}`;
|
|
79
|
+
return { verifier, challenge, uuid, loginUrl };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function poll(
|
|
83
|
+
uuid: string,
|
|
84
|
+
verifier: string,
|
|
85
|
+
): Promise<{ accessToken: string; refreshToken: string }> {
|
|
86
|
+
let delay = POLL_BASE_DELAY;
|
|
87
|
+
let consecutiveErrors = 0;
|
|
88
|
+
|
|
89
|
+
for (let attempt = 0; attempt < POLL_MAX_ATTEMPTS; attempt++) {
|
|
90
|
+
await sleepImpl(delay);
|
|
91
|
+
|
|
92
|
+
try {
|
|
93
|
+
const response = await fetchImpl(`${CURSOR_POLL_URL}?uuid=${uuid}&verifier=${verifier}`);
|
|
94
|
+
|
|
95
|
+
if (response.status === 404) {
|
|
96
|
+
consecutiveErrors = 0;
|
|
97
|
+
delay = Math.min(delay * POLL_BACKOFF_MULTIPLIER, POLL_MAX_DELAY);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (response.ok) {
|
|
102
|
+
const data = (await response.json()) as {
|
|
103
|
+
accessToken: string;
|
|
104
|
+
refreshToken: string;
|
|
105
|
+
};
|
|
106
|
+
return {
|
|
107
|
+
accessToken: data.accessToken,
|
|
108
|
+
refreshToken: data.refreshToken,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
throw new Error(`Poll failed: ${response.status}`);
|
|
113
|
+
} catch {
|
|
114
|
+
consecutiveErrors++;
|
|
115
|
+
if (consecutiveErrors >= 3) {
|
|
116
|
+
throw new Error("Too many consecutive errors during Cursor auth polling");
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
throw new Error("Cursor authentication polling timeout");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function refreshToken(refreshToken: string): Promise<CursorCredentials> {
|
|
125
|
+
const response = await fetchImpl(CURSOR_REFRESH_URL, {
|
|
126
|
+
method: "POST",
|
|
127
|
+
headers: {
|
|
128
|
+
Authorization: `Bearer ${refreshToken}`,
|
|
129
|
+
"Content-Type": "application/json",
|
|
130
|
+
},
|
|
131
|
+
body: "{}",
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
if (!response.ok) {
|
|
135
|
+
const error = await response.text();
|
|
136
|
+
throw new Error(`Cursor token refresh failed: ${error}`);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const data = (await response.json()) as {
|
|
140
|
+
accessToken: string;
|
|
141
|
+
refreshToken: string;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
access: data.accessToken,
|
|
146
|
+
refresh: data.refreshToken || refreshToken,
|
|
147
|
+
expires: getTokenExpiry(data.accessToken),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function login(callbacks: CursorAuthLoginCallbacks): Promise<CursorCredentials> {
|
|
152
|
+
const { verifier, uuid, loginUrl } = await generateParams();
|
|
153
|
+
await callbacks.onAuth({ url: loginUrl });
|
|
154
|
+
const { accessToken, refreshToken } = await poll(uuid, verifier);
|
|
155
|
+
return {
|
|
156
|
+
access: accessToken,
|
|
157
|
+
refresh: refreshToken,
|
|
158
|
+
expires: getTokenExpiry(accessToken),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return {
|
|
163
|
+
generateParams,
|
|
164
|
+
login,
|
|
165
|
+
poll,
|
|
166
|
+
refreshToken,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export async function generateCursorAuthParams(): Promise<CursorAuthParams> {
|
|
171
|
+
return createCursorAuthClient().generateParams();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ── Poll for auth completion ──
|
|
175
|
+
|
|
176
|
+
export async function pollCursorAuth(
|
|
177
|
+
uuid: string,
|
|
178
|
+
verifier: string,
|
|
179
|
+
): Promise<{ accessToken: string; refreshToken: string }> {
|
|
180
|
+
return createCursorAuthClient().poll(uuid, verifier);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// ── Token refresh ──
|
|
184
|
+
|
|
185
|
+
export interface CursorCredentials {
|
|
186
|
+
access: string;
|
|
187
|
+
refresh: string;
|
|
188
|
+
expires: number;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export async function refreshCursorToken(refreshToken: string): Promise<CursorCredentials> {
|
|
192
|
+
return createCursorAuthClient().refreshToken(refreshToken);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ── JWT expiry extraction ──
|
|
196
|
+
|
|
197
|
+
export function getCursorAccessTokenFromEnv(): string | undefined {
|
|
198
|
+
const token = process.env.CURSOR_ACCESS_TOKEN?.trim();
|
|
199
|
+
return token || undefined;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function getTokenExpiry(token: string): number {
|
|
203
|
+
try {
|
|
204
|
+
const parts = token.split(".");
|
|
205
|
+
if (parts.length !== 3 || !parts[1]) {
|
|
206
|
+
return Date.now() + 3600 * 1000;
|
|
207
|
+
}
|
|
208
|
+
const decoded = JSON.parse(atob(parts[1].replace(/-/g, "+").replace(/_/g, "/")));
|
|
209
|
+
if (decoded && typeof decoded === "object" && typeof decoded.exp === "number") {
|
|
210
|
+
return decoded.exp * 1000 - 5 * 60 * 1000;
|
|
211
|
+
}
|
|
212
|
+
} catch {}
|
|
213
|
+
return Date.now() + 3600 * 1000;
|
|
214
|
+
}
|