cursor-switch 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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +161 -0
  3. package/SECURITY.md +38 -0
  4. package/bin/cswitch.js +35 -0
  5. package/dist/cli.d.ts +6 -0
  6. package/dist/cli.js +850 -0
  7. package/dist/core/account-store.d.ts +25 -0
  8. package/dist/core/account-store.js +182 -0
  9. package/dist/core/cdp-engine.d.ts +75 -0
  10. package/dist/core/cdp-engine.js +320 -0
  11. package/dist/core/config-store.d.ts +38 -0
  12. package/dist/core/config-store.js +100 -0
  13. package/dist/core/cursor-paths.d.ts +22 -0
  14. package/dist/core/cursor-paths.js +287 -0
  15. package/dist/core/dashboard-launcher.d.ts +34 -0
  16. package/dist/core/dashboard-launcher.js +210 -0
  17. package/dist/core/fingerprint.d.ts +7 -0
  18. package/dist/core/fingerprint.js +34 -0
  19. package/dist/core/oauth-receiver.d.ts +31 -0
  20. package/dist/core/oauth-receiver.js +849 -0
  21. package/dist/core/official-api.d.ts +29 -0
  22. package/dist/core/official-api.js +205 -0
  23. package/dist/core/outlook-launcher.d.ts +54 -0
  24. package/dist/core/outlook-launcher.js +671 -0
  25. package/dist/core/process-manager.d.ts +25 -0
  26. package/dist/core/process-manager.js +133 -0
  27. package/dist/core/pure-login-service.d.ts +67 -0
  28. package/dist/core/pure-login-service.js +550 -0
  29. package/dist/core/refund-client.d.ts +102 -0
  30. package/dist/core/refund-client.js +221 -0
  31. package/dist/core/refund-service.d.ts +39 -0
  32. package/dist/core/refund-service.js +384 -0
  33. package/dist/core/sqlite-bridge.d.ts +23 -0
  34. package/dist/core/sqlite-bridge.js +207 -0
  35. package/dist/core/storage-bridge.d.ts +18 -0
  36. package/dist/core/storage-bridge.js +99 -0
  37. package/dist/core/token-parser.d.ts +35 -0
  38. package/dist/core/token-parser.js +106 -0
  39. package/dist/core/update-checker.d.ts +62 -0
  40. package/dist/core/update-checker.js +231 -0
  41. package/dist/index.d.ts +17 -0
  42. package/dist/index.js +17 -0
  43. package/dist/menu.d.ts +12 -0
  44. package/dist/menu.js +2201 -0
  45. package/dist/types.d.ts +60 -0
  46. package/dist/types.js +5 -0
  47. package/dist/utils/browser-utils.d.ts +31 -0
  48. package/dist/utils/browser-utils.js +283 -0
  49. package/dist/utils/clipboard.d.ts +5 -0
  50. package/dist/utils/clipboard.js +48 -0
  51. package/dist/utils/live-menu.d.ts +26 -0
  52. package/dist/utils/live-menu.js +169 -0
  53. package/dist/utils/plan-formatter.d.ts +30 -0
  54. package/dist/utils/plan-formatter.js +153 -0
  55. package/dist/utils/prompt-utils.d.ts +40 -0
  56. package/dist/utils/prompt-utils.js +105 -0
  57. package/dist/utils/security.d.ts +6 -0
  58. package/dist/utils/security.js +27 -0
  59. package/dist/utils/table-renderer.d.ts +7 -0
  60. package/dist/utils/table-renderer.js +88 -0
  61. package/dist/utils/time-formatter.d.ts +13 -0
  62. package/dist/utils/time-formatter.js +83 -0
  63. package/package.json +53 -0
@@ -0,0 +1,100 @@
1
+ /**
2
+ * 用户本地偏好配置仓库
3
+ * 存储路径: ~/.cursor-switch/config.json
4
+ * 用于记忆常用卡密、接口地址与个性化选项
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import os from 'node:os';
9
+ export class ConfigStore {
10
+ configDir;
11
+ configPath;
12
+ constructor() {
13
+ this.configDir = path.join(os.homedir(), '.cursor-switch');
14
+ this.configPath = path.join(this.configDir, 'config.json');
15
+ }
16
+ ensureDir() {
17
+ if (!fs.existsSync(this.configDir)) {
18
+ fs.mkdirSync(this.configDir, { recursive: true });
19
+ }
20
+ }
21
+ load() {
22
+ this.ensureDir();
23
+ if (!fs.existsSync(this.configPath)) {
24
+ return {};
25
+ }
26
+ try {
27
+ const data = fs.readFileSync(this.configPath, 'utf8');
28
+ return JSON.parse(data);
29
+ }
30
+ catch {
31
+ return {};
32
+ }
33
+ }
34
+ save(config) {
35
+ this.ensureDir();
36
+ try {
37
+ fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2), 'utf8');
38
+ }
39
+ catch { }
40
+ }
41
+ getSeatCardCode() {
42
+ const cfg = this.load();
43
+ return cfg.seat_card_code || null;
44
+ }
45
+ setSeatCardCode(code) {
46
+ const cfg = this.load();
47
+ cfg.seat_card_code = code.trim();
48
+ this.save(cfg);
49
+ }
50
+ getTokenCardCode() {
51
+ const cfg = this.load();
52
+ return cfg.token_card_code || null;
53
+ }
54
+ setTokenCardCode(code) {
55
+ const cfg = this.load();
56
+ cfg.token_card_code = code.trim();
57
+ this.save(cfg);
58
+ }
59
+ getSeatApiBase() {
60
+ const cfg = this.load();
61
+ const envVal = process.env.VITE_SEAT_API_BASE || process.env.CSWITCH_SEAT_API;
62
+ return (envVal || cfg.seat_api_base || 'https://getdoubao.com').replace(/\/+$/, '');
63
+ }
64
+ setSeatApiBase(url) {
65
+ const cfg = this.load();
66
+ cfg.seat_api_base = url.trim().replace(/\/+$/, '');
67
+ this.save(cfg);
68
+ }
69
+ getUpdateCache() {
70
+ const cfg = this.load();
71
+ return {
72
+ lastCheck: cfg.last_update_check,
73
+ latestVersion: cfg.latest_version,
74
+ };
75
+ }
76
+ setUpdateCache(latestVersion) {
77
+ const cfg = this.load();
78
+ cfg.last_update_check = Date.now();
79
+ cfg.latest_version = latestVersion.trim();
80
+ this.save(cfg);
81
+ }
82
+ getCustomExecutablePath() {
83
+ const cfg = this.load();
84
+ return cfg.custom_executable_path || null;
85
+ }
86
+ setCustomExecutablePath(pathStr) {
87
+ const cfg = this.load();
88
+ cfg.custom_executable_path = pathStr.trim();
89
+ this.save(cfg);
90
+ }
91
+ getCustomDataDir() {
92
+ const cfg = this.load();
93
+ return cfg.custom_data_dir || null;
94
+ }
95
+ setCustomDataDir(dirStr) {
96
+ const cfg = this.load();
97
+ cfg.custom_data_dir = dirStr.trim();
98
+ this.save(cfg);
99
+ }
100
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 全平台智能 Cursor 路径探测与解析引擎 (Windows / macOS / Linux)
3
+ * 具备 5 级弹性降级机制与零配置自愈能力:
4
+ * 1. 显式参数 / 环境变量 (CURSOR_PATH, CURSOR_DATA_DIR)
5
+ * 2. 本地用户偏好配置 (~/.cursor-switch/config.json)
6
+ * 3. 极速文件系统 / 多盘符扫描 (C..Z 盘符、scoop、chocolatey、/Applications 等,1-2ms)
7
+ * 4. 系统 PATH 命令反查与 CLI wrapper 溯源 (where.exe / which,10-20ms)
8
+ * 5. 运行中进程嗅探与操作系统索引检索 (PowerShell Get-Process / macOS Spotlight mdfind)
9
+ */
10
+ import type { ResolvedCursorPaths } from '../types.js';
11
+ /**
12
+ * 智能探测 Cursor 可执行文件路径
13
+ */
14
+ export declare function findCursorExecutable(customExecutablePath?: string): string | undefined;
15
+ /**
16
+ * 智能探测 Cursor 用户数据与存储目录 (包含 storage.json 与 state.vscdb)
17
+ */
18
+ export declare function findCursorDataDir(customDataPath?: string, executablePath?: string): string;
19
+ /**
20
+ * 完整解析所有 Cursor 关键路径
21
+ */
22
+ export declare function resolveCursorPaths(customPath?: string, customExecPath?: string): ResolvedCursorPaths;
@@ -0,0 +1,287 @@
1
+ /**
2
+ * 全平台智能 Cursor 路径探测与解析引擎 (Windows / macOS / Linux)
3
+ * 具备 5 级弹性降级机制与零配置自愈能力:
4
+ * 1. 显式参数 / 环境变量 (CURSOR_PATH, CURSOR_DATA_DIR)
5
+ * 2. 本地用户偏好配置 (~/.cursor-switch/config.json)
6
+ * 3. 极速文件系统 / 多盘符扫描 (C..Z 盘符、scoop、chocolatey、/Applications 等,1-2ms)
7
+ * 4. 系统 PATH 命令反查与 CLI wrapper 溯源 (where.exe / which,10-20ms)
8
+ * 5. 运行中进程嗅探与操作系统索引检索 (PowerShell Get-Process / macOS Spotlight mdfind)
9
+ */
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import fs from 'node:fs';
13
+ import { execSync } from 'node:child_process';
14
+ import { ConfigStore } from './config-store.js';
15
+ /**
16
+ * 从 VSCode / Cursor 的 CLI 启动脚本 (如 resources/app/bin/cursor) 溯源主程序绝对路径
17
+ */
18
+ function resolveExeFromCliScript(scriptPath) {
19
+ try {
20
+ const real = fs.realpathSync(scriptPath);
21
+ let currentDir = path.dirname(real);
22
+ for (let i = 0; i < 5; i++) {
23
+ if (process.platform === 'win32') {
24
+ const winExe = path.join(currentDir, 'Cursor.exe');
25
+ if (fs.existsSync(winExe))
26
+ return winExe;
27
+ }
28
+ else if (process.platform === 'darwin') {
29
+ const macExe = path.join(currentDir, 'MacOS', 'Cursor');
30
+ if (fs.existsSync(macExe))
31
+ return macExe;
32
+ }
33
+ else {
34
+ const linuxExe = path.join(currentDir, 'cursor');
35
+ if (fs.existsSync(linuxExe) && linuxExe !== real && fs.statSync(linuxExe).isFile())
36
+ return linuxExe;
37
+ }
38
+ const parent = path.dirname(currentDir);
39
+ if (parent === currentDir)
40
+ break;
41
+ currentDir = parent;
42
+ }
43
+ }
44
+ catch { }
45
+ return null;
46
+ }
47
+ /**
48
+ * 智能探测 Cursor 可执行文件路径
49
+ */
50
+ export function findCursorExecutable(customExecutablePath) {
51
+ const config = new ConfigStore();
52
+ // 1. 显式入参
53
+ if (customExecutablePath && fs.existsSync(customExecutablePath)) {
54
+ return customExecutablePath;
55
+ }
56
+ // 2. 环境变量 (方便 CI/CD 或终端用户自设)
57
+ const envPath = process.env.CURSOR_PATH || process.env.CURSOR_BIN || process.env.CURSOR_EXEC_PATH;
58
+ if (envPath && fs.existsSync(envPath)) {
59
+ return envPath;
60
+ }
61
+ // 3. 用户偏好配置缓存 (0ms)
62
+ const cachedPath = config.getCustomExecutablePath();
63
+ if (cachedPath && fs.existsSync(cachedPath)) {
64
+ return cachedPath;
65
+ }
66
+ const platform = process.platform;
67
+ // 4. 极速文件系统 / 多盘符扫描 (< 2ms)
68
+ if (platform === 'win32') {
69
+ const localAppData = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
70
+ const directCandidates = [
71
+ path.join(localAppData, 'Programs', 'cursor', 'Cursor.exe'),
72
+ path.join(localAppData, 'Programs', 'Cursor', 'Cursor.exe'),
73
+ path.join(os.homedir(), 'scoop', 'apps', 'cursor', 'current', 'Cursor.exe'),
74
+ path.join(process.env.ALLUSERSPROFILE || 'C:\\ProgramData', 'chocolatey', 'bin', 'Cursor.exe'),
75
+ ];
76
+ for (const cand of directCandidates) {
77
+ if (fs.existsSync(cand)) {
78
+ config.setCustomExecutablePath(cand);
79
+ return cand;
80
+ }
81
+ }
82
+ // 扫描 Windows 所有可用盘符 (支持 D/E/F/G 等非系统盘或外接扩展盘)
83
+ const driveLetters = ['C', 'D', 'E', 'F', 'G', 'H', 'X', 'Y', 'Z'];
84
+ for (const d of driveLetters) {
85
+ const root = `${d}:\\`;
86
+ if (!fs.existsSync(root))
87
+ continue;
88
+ const subDirs = [
89
+ 'Program Files\\cursor\\Cursor.exe',
90
+ 'Program Files\\Cursor\\Cursor.exe',
91
+ 'Program Files (x86)\\cursor\\Cursor.exe',
92
+ 'Program Files (x86)\\Cursor\\Cursor.exe',
93
+ 'Cursor\\Cursor.exe',
94
+ 'cursor\\Cursor.exe',
95
+ 'Software\\Cursor\\Cursor.exe',
96
+ 'Software\\cursor\\Cursor.exe',
97
+ 'Tools\\Cursor\\Cursor.exe',
98
+ 'Tools\\cursor\\Cursor.exe',
99
+ 'Apps\\Cursor\\Cursor.exe',
100
+ ];
101
+ for (const sub of subDirs) {
102
+ const cand = path.join(root, sub);
103
+ if (fs.existsSync(cand)) {
104
+ config.setCustomExecutablePath(cand);
105
+ return cand;
106
+ }
107
+ }
108
+ }
109
+ }
110
+ else if (platform === 'darwin') {
111
+ const macCandidates = [
112
+ '/Applications/Cursor.app/Contents/MacOS/Cursor',
113
+ path.join(os.homedir(), 'Applications', 'Cursor.app', 'Contents', 'MacOS', 'Cursor'),
114
+ '/opt/homebrew-cask/Caskroom/cursor/latest/Cursor.app/Contents/MacOS/Cursor',
115
+ ];
116
+ for (const cand of macCandidates) {
117
+ if (fs.existsSync(cand)) {
118
+ config.setCustomExecutablePath(cand);
119
+ return cand;
120
+ }
121
+ }
122
+ }
123
+ else {
124
+ // Linux
125
+ const linuxCandidates = [
126
+ '/usr/bin/cursor',
127
+ '/usr/local/bin/cursor',
128
+ '/opt/Cursor/cursor',
129
+ '/opt/cursor/cursor',
130
+ path.join(os.homedir(), '.local', 'bin', 'cursor'),
131
+ '/snap/bin/cursor',
132
+ '/var/lib/snapd/snap/bin/cursor',
133
+ ];
134
+ for (const cand of linuxCandidates) {
135
+ if (fs.existsSync(cand)) {
136
+ config.setCustomExecutablePath(cand);
137
+ return cand;
138
+ }
139
+ }
140
+ }
141
+ // 5. 系统 PATH 命令反查 (`where.exe cursor` / `which cursor`)
142
+ try {
143
+ const cmd = platform === 'win32' ? 'where.exe cursor' : 'which cursor';
144
+ const stdout = execSync(cmd, {
145
+ encoding: 'utf8',
146
+ stdio: ['ignore', 'pipe', 'ignore'],
147
+ windowsHide: true,
148
+ timeout: 1500,
149
+ }).trim();
150
+ if (stdout) {
151
+ const lines = stdout.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
152
+ for (const line of lines) {
153
+ if (fs.existsSync(line)) {
154
+ if (line.toLowerCase().endsWith('.exe')) {
155
+ config.setCustomExecutablePath(line);
156
+ return line;
157
+ }
158
+ const unrolled = resolveExeFromCliScript(line);
159
+ if (unrolled) {
160
+ config.setCustomExecutablePath(unrolled);
161
+ return unrolled;
162
+ }
163
+ }
164
+ }
165
+ }
166
+ }
167
+ catch { }
168
+ // 6. macOS Spotlight 检索 (针对用户自定义存放在 ~/Downloads、移动硬盘等非标准位置)
169
+ if (platform === 'darwin') {
170
+ try {
171
+ const stdout = execSync('mdfind "kMDItemFSName == \'Cursor.app\'"', {
172
+ encoding: 'utf8',
173
+ stdio: ['ignore', 'pipe', 'ignore'],
174
+ timeout: 1500,
175
+ }).trim();
176
+ if (stdout) {
177
+ const appPath = stdout.split('\n')[0].trim();
178
+ const cand = path.join(appPath, 'Contents', 'MacOS', 'Cursor');
179
+ if (fs.existsSync(cand)) {
180
+ config.setCustomExecutablePath(cand);
181
+ return cand;
182
+ }
183
+ }
184
+ }
185
+ catch { }
186
+ }
187
+ // 7. 运行中进程反查 (若用户当前已打开 Cursor,从活动句柄直接捕获路径)
188
+ try {
189
+ if (platform === 'win32') {
190
+ const stdout = execSync('powershell -NoProfile -NonInteractive -Command "(Get-Process Cursor -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Path -First 1)"', {
191
+ encoding: 'utf8',
192
+ stdio: ['ignore', 'pipe', 'ignore'],
193
+ windowsHide: true,
194
+ timeout: 1500,
195
+ }).trim();
196
+ if (stdout && fs.existsSync(stdout)) {
197
+ config.setCustomExecutablePath(stdout);
198
+ return stdout;
199
+ }
200
+ }
201
+ }
202
+ catch { }
203
+ return undefined;
204
+ }
205
+ /**
206
+ * 智能探测 Cursor 用户数据与存储目录 (包含 storage.json 与 state.vscdb)
207
+ */
208
+ export function findCursorDataDir(customDataPath, executablePath) {
209
+ const config = new ConfigStore();
210
+ // 1. 显式入参
211
+ if (customDataPath && fs.existsSync(customDataPath)) {
212
+ return customDataPath;
213
+ }
214
+ // 2. 环境变量
215
+ const envData = process.env.CURSOR_DATA_DIR || process.env.CURSOR_STORAGE_DIR;
216
+ if (envData && fs.existsSync(envData)) {
217
+ return envData;
218
+ }
219
+ // 3. 用户偏好配置缓存
220
+ const cachedDir = config.getCustomDataDir();
221
+ if (cachedDir && fs.existsSync(cachedDir)) {
222
+ return cachedDir;
223
+ }
224
+ const platform = process.platform;
225
+ let standardDir = '';
226
+ if (platform === 'win32') {
227
+ const appData = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming');
228
+ standardDir = path.join(appData, 'Cursor', 'User', 'globalStorage');
229
+ }
230
+ else if (platform === 'darwin') {
231
+ standardDir = path.join(os.homedir(), 'Library', 'Application Support', 'Cursor', 'User', 'globalStorage');
232
+ }
233
+ else {
234
+ const configHome = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
235
+ standardDir = path.join(configHome, 'Cursor', 'User', 'globalStorage');
236
+ }
237
+ if (fs.existsSync(standardDir)) {
238
+ return standardDir;
239
+ }
240
+ // 4. 便携版模式探测: 如果 Cursor 为绿色便携版,数据存储在可执行文件同级的 data/ 目录
241
+ if (executablePath) {
242
+ const exeDir = path.dirname(executablePath);
243
+ const portableCandidates = [
244
+ path.join(exeDir, 'data', 'user-data', 'User', 'globalStorage'),
245
+ path.join(exeDir, 'data', 'User', 'globalStorage'),
246
+ path.join(exeDir, '..', 'data', 'user-data', 'User', 'globalStorage'),
247
+ ];
248
+ for (const cand of portableCandidates) {
249
+ if (fs.existsSync(cand)) {
250
+ config.setCustomDataDir(cand);
251
+ return cand;
252
+ }
253
+ }
254
+ }
255
+ // 5. Scoop 便携数据持久化目录
256
+ if (platform === 'win32') {
257
+ const scoopData = path.join(os.homedir(), 'scoop', 'persist', 'cursor', 'data', 'User', 'globalStorage');
258
+ if (fs.existsSync(scoopData)) {
259
+ config.setCustomDataDir(scoopData);
260
+ return scoopData;
261
+ }
262
+ }
263
+ // 6. Linux Snap 数据目录
264
+ if (platform === 'linux') {
265
+ const snapData = path.join(os.homedir(), 'snap', 'cursor', 'current', '.config', 'Cursor', 'User', 'globalStorage');
266
+ if (fs.existsSync(snapData)) {
267
+ config.setCustomDataDir(snapData);
268
+ return snapData;
269
+ }
270
+ }
271
+ // 默认返回标准目录 (如果首次启动尚未生成,后续 StorageBridge 会自动 mkdirSync)
272
+ return standardDir;
273
+ }
274
+ /**
275
+ * 完整解析所有 Cursor 关键路径
276
+ */
277
+ export function resolveCursorPaths(customPath, customExecPath) {
278
+ const executablePath = findCursorExecutable(customExecPath);
279
+ const dataDir = findCursorDataDir(customPath, executablePath);
280
+ const storageJson = path.join(dataDir, 'storage.json');
281
+ const sqliteDb = path.join(dataDir, 'state.vscdb');
282
+ return {
283
+ storageJson,
284
+ sqliteDb,
285
+ executablePath,
286
+ };
287
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * 官网后台 (Cursor Dashboard) 免密直通模块
3
+ * 原生 CDP 零依赖免密直通 (系统 Chrome/Edge/Chromium + CDP Cookie 物理注入)
4
+ * 智能支持在当前已有独立浏览器实例 (如 Outlook) 中开新标签页,或开启全新独立隔离浏览器实例
5
+ */
6
+ import type { AccountInfo } from '../types.js';
7
+ export interface DashboardOpenOptions {
8
+ account?: AccountInfo;
9
+ token?: string;
10
+ email?: string;
11
+ cdpPort?: number;
12
+ }
13
+ export declare class DashboardLauncher {
14
+ /**
15
+ * 获取 Cursor 控制台专用独立隔离 Profile 目录
16
+ */
17
+ static getDashboardProfileDir(email: string): string;
18
+ /**
19
+ * 打开指定账号的 Cursor 官网后台 (免密直达)
20
+ */
21
+ static openDashboard(account: AccountInfo, options?: Partial<DashboardOpenOptions>): Promise<boolean>;
22
+ /**
23
+ * 直接通过 Token 凭据免密打开 Cursor 官网后台
24
+ */
25
+ static openDashboardWithToken(token: string, email?: string, cdpPort?: number): Promise<boolean>;
26
+ /**
27
+ * 核心逻辑:优先使用原生 CDP 独立浏览器免密注入,优雅降级到 Python 或默认浏览器
28
+ */
29
+ private static openWithCdpOrFallback;
30
+ /**
31
+ * 使用原生 CDP 启动独立 Chromium 浏览器并注入 Cookie 直达后台
32
+ */
33
+ static openWithCdp(token: string, email: string, existingCdpPort?: number): Promise<boolean>;
34
+ }
@@ -0,0 +1,210 @@
1
+ /**
2
+ * 官网后台 (Cursor Dashboard) 免密直通模块
3
+ * 原生 CDP 零依赖免密直通 (系统 Chrome/Edge/Chromium + CDP Cookie 物理注入)
4
+ * 智能支持在当前已有独立浏览器实例 (如 Outlook) 中开新标签页,或开启全新独立隔离浏览器实例
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { spawn } from 'node:child_process';
9
+ import chalk from 'chalk';
10
+ import boxen from 'boxen';
11
+ import { CdpEngine } from './cdp-engine.js';
12
+ import { findInstalledBrowsers, openBrowserUrl, findPythonDashboardScript, getCookieInjectionSnippet } from '../utils/browser-utils.js';
13
+ export class DashboardLauncher {
14
+ /**
15
+ * 获取 Cursor 控制台专用独立隔离 Profile 目录
16
+ */
17
+ static getDashboardProfileDir(email) {
18
+ const safeName = email
19
+ .trim()
20
+ .toLowerCase()
21
+ .replace(/[^a-z0-9._-]/g, '_')
22
+ .replace(/^_+|_+$/g, '');
23
+ const baseDir = process.platform === 'win32'
24
+ ? path.join(process.env.LOCALAPPDATA || path.join(process.env.USERPROFILE || 'C:\\', 'AppData', 'Local'), '.cursor-switch', 'cursor-profiles')
25
+ : path.join(process.env.HOME || '~', '.cursor-switch', 'cursor-profiles');
26
+ const profileDir = path.join(baseDir, safeName || 'default_user');
27
+ if (!fs.existsSync(profileDir)) {
28
+ fs.mkdirSync(profileDir, { recursive: true });
29
+ }
30
+ return profileDir;
31
+ }
32
+ /**
33
+ * 打开指定账号的 Cursor 官网后台 (免密直达)
34
+ */
35
+ static async openDashboard(account, options = {}) {
36
+ const sessionToken = options.token ||
37
+ account.workos_cursor_session_token ||
38
+ (account.token && account.token.includes('::') ? account.token : null) ||
39
+ account.token;
40
+ const email = options.email || account.email || 'Cursor User';
41
+ return this.openWithCdpOrFallback(sessionToken, email, options.cdpPort);
42
+ }
43
+ /**
44
+ * 直接通过 Token 凭据免密打开 Cursor 官网后台
45
+ */
46
+ static async openDashboardWithToken(token, email = 'Token User', cdpPort) {
47
+ return this.openWithCdpOrFallback(token.trim(), email, cdpPort);
48
+ }
49
+ /**
50
+ * 核心逻辑:优先使用原生 CDP 独立浏览器免密注入,优雅降级到 Python 或默认浏览器
51
+ */
52
+ static async openWithCdpOrFallback(sessionToken, email, cdpPort) {
53
+ const dashboardUrl = 'https://cursor.com/cn/dashboard';
54
+ const cleanToken = (sessionToken || '').trim().replace(/["\r\n]/g, '');
55
+ // 1. 优先尝试:使用原生 CDP 引擎免密直达 (纯 Node.js,零依赖,秒开)
56
+ if (cleanToken) {
57
+ try {
58
+ const cdpSuccess = await this.openWithCdp(cleanToken, email, cdpPort);
59
+ if (cdpSuccess) {
60
+ return true;
61
+ }
62
+ }
63
+ catch {
64
+ // CDP 尝试失败,优雅降级至备选通道
65
+ }
66
+ }
67
+ // 2. 备选通道:动态探测本地 Python 注入脚本
68
+ const pyScript = findPythonDashboardScript();
69
+ if (pyScript && cleanToken) {
70
+ try {
71
+ if (pyScript.endsWith('.cmd')) {
72
+ const child = spawn('cmd.exe', ['/c', pyScript, '--token', cleanToken], {
73
+ detached: true,
74
+ stdio: 'ignore',
75
+ });
76
+ child.unref();
77
+ return true;
78
+ }
79
+ else if (pyScript.endsWith('.py')) {
80
+ const pyCmd = process.platform === 'win32' ? 'python' : 'python3';
81
+ const child = spawn(pyCmd, [pyScript, '--token', cleanToken], {
82
+ detached: true,
83
+ stdio: 'ignore',
84
+ });
85
+ child.unref();
86
+ return true;
87
+ }
88
+ }
89
+ catch { }
90
+ }
91
+ // 3. 最终兜底:调起系统默认浏览器 + 打印 1 行 Console 快速注入指令
92
+ const opened = await openBrowserUrl(dashboardUrl);
93
+ if (cleanToken) {
94
+ const snippet = getCookieInjectionSnippet(cleanToken);
95
+ console.log(boxen([
96
+ chalk.bold.cyan('🌐 已尝试调起默认浏览器访问 Cursor 官网控制台'),
97
+ chalk.dim('────────────────────────────────────────────────────────────'),
98
+ ` 账号邮箱 : ${chalk.bold.yellow(email)}`,
99
+ ` 目标网址 : ${chalk.underline.white(dashboardUrl)}`,
100
+ '',
101
+ chalk.bold.green('💡【全浏览器免密直达技巧 (Chrome / Edge / Safari / Arc / Firefox)】:'),
102
+ chalk.grey('若您的浏览器当前处于未登录状态,无需输入密码,只需 3 秒:'),
103
+ `1. 在打开的网页任意空白处按 ${chalk.yellow('F12')} (Mac 快捷键: ${chalk.yellow('⌥⌘I')}) 切换至 ${chalk.white('Console (控制台)')}`,
104
+ '2. 粘贴以下代码并敲回车,网页将瞬间自动免密登录直达控制台:',
105
+ chalk.dim('────────────────────────────────────────────────────────────'),
106
+ chalk.cyanBright(snippet),
107
+ ].join('\n'), {
108
+ padding: { top: 0, bottom: 0, left: 1, right: 1 },
109
+ borderColor: 'cyan',
110
+ borderStyle: 'round',
111
+ }));
112
+ }
113
+ return opened;
114
+ }
115
+ /**
116
+ * 使用原生 CDP 启动独立 Chromium 浏览器并注入 Cookie 直达后台
117
+ */
118
+ static async openWithCdp(token, email, existingCdpPort) {
119
+ const installed = findInstalledBrowsers();
120
+ const chrome = installed.find((b) => b.name.includes('Chrome'));
121
+ const edge = installed.find((b) => b.name.includes('Edge'));
122
+ const brave = installed.find((b) => b.name.includes('Brave'));
123
+ const anyChromium = installed.find((b) => b.name.includes('Chromium') ||
124
+ b.path.toLowerCase().endsWith('chrome.exe') ||
125
+ b.path.toLowerCase().endsWith('msedge.exe'));
126
+ const selectedBrowser = chrome || edge || brave || anyChromium || installed[0];
127
+ if (!selectedBrowser || !fs.existsSync(selectedBrowser.path)) {
128
+ return false;
129
+ }
130
+ const dashboardUrl = 'https://cursor.com/cn/dashboard';
131
+ let cdpPort = existingCdpPort;
132
+ let isNewInstance = false;
133
+ if (!cdpPort) {
134
+ try {
135
+ cdpPort = await CdpEngine.getFreePort();
136
+ }
137
+ catch {
138
+ cdpPort = 9223;
139
+ }
140
+ isNewInstance = true;
141
+ const profileDir = this.getDashboardProfileDir(email);
142
+ const launchArgs = [
143
+ `--user-data-dir=${profileDir}`,
144
+ `--remote-debugging-port=${cdpPort}`,
145
+ '--remote-debugging-address=127.0.0.1',
146
+ '--remote-allow-origins=*',
147
+ '--new-window',
148
+ '--no-first-run',
149
+ '--no-default-browser-check',
150
+ 'about:blank',
151
+ ];
152
+ const child = spawn(selectedBrowser.path, launchArgs, {
153
+ detached: true,
154
+ stdio: 'ignore',
155
+ windowsHide: false,
156
+ });
157
+ child.unref();
158
+ }
159
+ // 等待并连接 CDP
160
+ const target = await CdpEngine.waitForPageTarget(cdpPort, 12000);
161
+ if (!target || !target.webSocketDebuggerUrl) {
162
+ return false;
163
+ }
164
+ const cdp = new CdpEngine(target.webSocketDebuggerUrl);
165
+ await cdp.connect(8000);
166
+ await cdp.send('Page.enable');
167
+ await cdp.send('Network.enable');
168
+ // 1. 物理注入 Cursor Session Token Cookie (长期有效)
169
+ await cdp.send('Network.setCookie', {
170
+ name: 'WorkosCursorSessionToken',
171
+ value: token,
172
+ domain: '.cursor.com',
173
+ path: '/',
174
+ secure: true,
175
+ httpOnly: false,
176
+ sameSite: 'Lax',
177
+ expires: Math.floor(Date.now() / 1000) + 365 * 86400,
178
+ });
179
+ // 2. 注入默认中文语言环境
180
+ await cdp.send('Network.setCookie', {
181
+ name: 'NEXT_LOCALE',
182
+ value: 'zh-CN',
183
+ domain: '.cursor.com',
184
+ path: '/',
185
+ expires: Math.floor(Date.now() / 1000) + 365 * 86400,
186
+ });
187
+ // 3. 导航到 Dashboard (若为已有浏览器实例,则新开标签页)
188
+ if (isNewInstance) {
189
+ await cdp.navigate(dashboardUrl);
190
+ }
191
+ else {
192
+ await cdp.send('Target.createTarget', { url: dashboardUrl });
193
+ }
194
+ await cdp.bringToFront();
195
+ cdp.disconnect();
196
+ console.log(boxen([
197
+ chalk.bold.green('✔ Cursor 官网控制台已成功免密直达'),
198
+ chalk.dim('────────────────────────────────────────────────────────────'),
199
+ ` 账号邮箱 : ${chalk.bold.white(email)}`,
200
+ ` 控制台页 : ${chalk.cyan(dashboardUrl)}`,
201
+ ` 运行模式 : ${chalk.green(isNewInstance ? '● 独立隔离浏览器 (原生 CDP 零依赖免密直通)' : '● 当前浏览器新标签页 (已自动免密登录)')}`,
202
+ ` 会话凭据 : ${chalk.grey('WorkosCursorSessionToken 已自动写入 CookieJar')}`,
203
+ ].join('\n'), {
204
+ padding: { top: 0, bottom: 0, left: 1, right: 1 },
205
+ borderColor: 'green',
206
+ borderStyle: 'round',
207
+ }));
208
+ return true;
209
+ }
210
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Cursor 专属防封机器码 (Virtual Machine ID) 生成与管理引擎
3
+ * 对齐官方指纹规范:UUID v4 + SHA-256 + SHA-512 体系
4
+ */
5
+ import type { MachineIds } from '../types.js';
6
+ export declare function generateMachineIds(): MachineIds;
7
+ export declare function formatMachineIdSummary(ids?: MachineIds): string;