cursor-switch 1.0.6 → 1.0.8

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 (84) hide show
  1. package/README.md +76 -75
  2. package/SECURITY.md +22 -19
  3. package/bin/cswitch.js +31 -8
  4. package/dist/cli.d.ts +0 -4
  5. package/dist/cli.js +404 -225
  6. package/dist/core/account-store.d.ts +0 -7
  7. package/dist/core/account-store.js +22 -28
  8. package/dist/core/cdp-engine.d.ts +11 -49
  9. package/dist/core/cdp-engine.js +155 -110
  10. package/dist/core/config-store.d.ts +7 -6
  11. package/dist/core/config-store.js +33 -12
  12. package/dist/core/cursor-paths.d.ts +8 -18
  13. package/dist/core/cursor-paths.js +18 -37
  14. package/dist/core/dashboard-launcher.d.ts +2 -22
  15. package/dist/core/dashboard-launcher.js +10 -60
  16. package/dist/core/extract-client.d.ts +57 -0
  17. package/dist/core/extract-client.js +219 -0
  18. package/dist/core/extract-menu.d.ts +3 -0
  19. package/dist/core/extract-menu.js +360 -0
  20. package/dist/core/extract-service.d.ts +64 -0
  21. package/dist/core/extract-service.js +435 -0
  22. package/dist/core/fingerprint.d.ts +0 -4
  23. package/dist/core/fingerprint.js +0 -6
  24. package/dist/core/oauth-receiver.d.ts +1 -11
  25. package/dist/core/oauth-receiver.js +509 -527
  26. package/dist/core/official-api.d.ts +0 -17
  27. package/dist/core/official-api.js +4 -23
  28. package/dist/core/outlook-launcher.d.ts +0 -27
  29. package/dist/core/outlook-launcher.js +235 -261
  30. package/dist/core/process-manager.d.ts +0 -14
  31. package/dist/core/process-manager.js +7 -22
  32. package/dist/core/pure-login-service.d.ts +64 -28
  33. package/dist/core/pure-login-service.js +527 -346
  34. package/dist/core/refund-client.d.ts +0 -22
  35. package/dist/core/refund-client.js +7 -27
  36. package/dist/core/refund-service.d.ts +0 -16
  37. package/dist/core/refund-service.js +8 -34
  38. package/dist/core/safe-storage.d.ts +27 -0
  39. package/dist/core/safe-storage.js +284 -0
  40. package/dist/core/sqlite-bridge.d.ts +10 -11
  41. package/dist/core/sqlite-bridge.js +112 -47
  42. package/dist/core/storage-bridge.d.ts +14 -5
  43. package/dist/core/storage-bridge.js +84 -24
  44. package/dist/core/switch-orchestrator.d.ts +96 -0
  45. package/dist/core/switch-orchestrator.js +341 -0
  46. package/dist/core/token-exchange.d.ts +81 -0
  47. package/dist/core/token-exchange.js +275 -0
  48. package/dist/core/token-parser.d.ts +56 -20
  49. package/dist/core/token-parser.js +354 -43
  50. package/dist/core/update-checker.d.ts +1 -29
  51. package/dist/core/update-checker.js +28 -43
  52. package/dist/index.d.ts +1 -3
  53. package/dist/index.js +1 -3
  54. package/dist/menu.d.ts +0 -7
  55. package/dist/menu.js +445 -538
  56. package/dist/types.d.ts +12 -4
  57. package/dist/types.js +0 -4
  58. package/dist/utils/account-text-importer.d.ts +9 -0
  59. package/dist/utils/account-text-importer.js +96 -0
  60. package/dist/utils/browser-utils.d.ts +0 -24
  61. package/dist/utils/browser-utils.js +0 -57
  62. package/dist/utils/clipboard.d.ts +0 -4
  63. package/dist/utils/clipboard.js +0 -5
  64. package/dist/utils/credential-bundle-ui.d.ts +36 -0
  65. package/dist/utils/credential-bundle-ui.js +246 -0
  66. package/dist/utils/live-menu.d.ts +37 -9
  67. package/dist/utils/live-menu.js +510 -81
  68. package/dist/utils/plan-formatter.d.ts +0 -26
  69. package/dist/utils/plan-formatter.js +10 -44
  70. package/dist/utils/prompt-utils.d.ts +0 -18
  71. package/dist/utils/prompt-utils.js +0 -23
  72. package/dist/utils/proxy-bootstrap.d.ts +12 -0
  73. package/dist/utils/proxy-bootstrap.js +141 -0
  74. package/dist/utils/security.d.ts +2 -4
  75. package/dist/utils/security.js +36 -4
  76. package/dist/utils/table-renderer.d.ts +0 -4
  77. package/dist/utils/table-renderer.js +24 -8
  78. package/dist/utils/time-formatter.d.ts +0 -4
  79. package/dist/utils/time-formatter.js +0 -8
  80. package/dist/utils/token-preflight-ui.d.ts +28 -0
  81. package/dist/utils/token-preflight-ui.js +222 -0
  82. package/dist/utils/window-focus.d.ts +3 -0
  83. package/dist/utils/window-focus.js +106 -0
  84. package/package.json +12 -5
package/dist/cli.js CHANGED
@@ -1,7 +1,3 @@
1
- /**
2
- * Commander 纯命令行入口
3
- * 支持非交互式 CLI Flags 与一键极速命令
4
- */
5
1
  import { Command } from 'commander';
6
2
  import chalk from 'chalk';
7
3
  import fs from 'node:fs';
@@ -16,28 +12,34 @@ import { OAuthReceiver } from './core/oauth-receiver.js';
16
12
  import { TokenParser } from './core/token-parser.js';
17
13
  import { generateMachineIds, formatMachineIdSummary } from './core/fingerprint.js';
18
14
  import { OfficialApiClient } from './core/official-api.js';
15
+ import { applyMachineIdsToCursor, executeAccountSwitch, readLocalCursorAuth, } from './core/switch-orchestrator.js';
16
+ import { applyParsedCredentialToAccount, buildOAuthAccountInfo, upgradeAccountWebTokenOnIngest, } from './core/token-exchange.js';
19
17
  import { renderAccountTable } from './utils/table-renderer.js';
20
18
  import { getExpiryStatus } from './utils/time-formatter.js';
21
- import { maskToken } from './utils/security.js';
19
+ import { maskToken, writeSecureFileSync } from './utils/security.js';
22
20
  import { formatPlanName, formatPlanBadge } from './utils/plan-formatter.js';
21
+ import { printFactualTokenStatus, printIngestUpgradeResult, resolveStaleSwitchWithHealing, } from './utils/token-preflight-ui.js';
22
+ import { copyPreferredAccountCredential, normalizeCopyFormatInput, printExtractedCredentialsResult, renderCredentialSummaryLines, runInteractiveCopyAccountMenu, } from './utils/credential-bundle-ui.js';
23
23
  import { runInteractiveMenu, handleAccountCleanupMenu } from './menu.js';
24
24
  import { RefundService } from './core/refund-service.js';
25
+ import { ExtractService } from './core/extract-service.js';
26
+ import { normalizeExtractTier } from './core/extract-client.js';
25
27
  import { PureLoginService } from './core/pure-login-service.js';
26
28
  import { UpdateChecker, CURRENT_VERSION } from './core/update-checker.js';
29
+ import { importAccountsFromText } from './utils/account-text-importer.js';
27
30
  import boxen from 'boxen';
28
- import { copyToClipboard } from './utils/clipboard.js';
29
31
  import { safeInput } from './utils/prompt-utils.js';
32
+ import { ensureGlobalProxy } from './utils/proxy-bootstrap.js';
30
33
  export function createCli() {
34
+ ensureGlobalProxy();
31
35
  const program = new Command();
32
36
  program
33
37
  .name('cswitch')
34
38
  .description('Cursor IDE 极速、安全、纯本地运行的多账号与防封虚拟机器指纹管理工具')
35
39
  .version(CURRENT_VERSION)
36
40
  .action(async () => {
37
- // 无参数时默认进入交互式主菜单
38
41
  await runInteractiveMenu();
39
42
  });
40
- // 1. current / whoami
41
43
  program
42
44
  .command('current')
43
45
  .alias('whoami')
@@ -47,8 +49,9 @@ export function createCli() {
47
49
  const storage = new StorageBridge(paths.storageJson);
48
50
  const sqlite = new SqliteBridge(paths.sqliteDb);
49
51
  const store = new AccountStore();
50
- const email = storage.readCurrentEmail() || (await sqlite.readEmail()) || '未登录';
51
- const token = storage.readCurrentToken() || (await sqlite.readToken()) || '';
52
+ const localAuth = await readLocalCursorAuth(storage, sqlite);
53
+ const email = localAuth.email || '未登录';
54
+ const token = localAuth.token || '';
52
55
  const machineIds = storage.readMachineIds();
53
56
  const acc = store.getByEmail(email);
54
57
  const expiry = getExpiryStatus(acc?.current_period_usage?.billingCycleEnd);
@@ -56,11 +59,13 @@ export function createCli() {
56
59
  console.log(`• 登录邮箱 : ${chalk.bold.white(email)}`);
57
60
  console.log(`• 会员级别 : ${formatPlanBadge(acc?.subscription_type)}`);
58
61
  console.log(`• 具体到期 : ${chalk.blue(expiry.formattedDate)} (${expiry.countdownText})`);
59
- console.log(`• 凭据 Token : ${chalk.grey(maskToken(token))}`);
62
+ console.log(`• 凭据 Token : ${chalk.grey(maskToken(token))}${localAuth.decrypted ? chalk.grey(' (safeStorage 已解密)') : ''}`);
63
+ if (localAuth.isEncrypted && !localAuth.token) {
64
+ console.log(chalk.yellow(`• 解密提示 : 检测到新版 safeStorage 加密凭据 (${localAuth.encryptionError || '当前环境无法解密'})`));
65
+ }
60
66
  console.log(`• 机器指纹 : ${chalk.magenta(formatMachineIdSummary(machineIds))}`);
61
67
  console.log(`• Cursor进程 : ${ProcessManager.isCursorRunning() ? chalk.green('● 运行中') : chalk.grey('○ 未运行')}\n`);
62
68
  });
63
- // 2. list / ls
64
69
  program
65
70
  .command('list')
66
71
  .alias('ls')
@@ -92,7 +97,6 @@ export function createCli() {
92
97
  const limit = options.limit !== undefined ? Number(options.limit) : 20;
93
98
  let displayAccounts = accounts;
94
99
  if (limit > 0 && accounts.length > limit) {
95
- // 优先将当前在用的账号排在最前面
96
100
  displayAccounts = [
97
101
  ...accounts.filter((a) => a.is_current),
98
102
  ...accounts.filter((a) => !a.is_current),
@@ -103,19 +107,23 @@ export function createCli() {
103
107
  console.log(chalk.grey(` 提示: 当前展示前 ${limit} 个账号 (本地总计 ${totalCount} 个)。查看全部请加参数: cswitch list -l 0 或模糊搜索: cswitch list -s <关键词>\n`));
104
108
  }
105
109
  });
106
- // 3. use / switch
107
110
  program
108
111
  .command('use <identifier>')
109
112
  .alias('switch')
110
113
  .description('一键切换到指定账号 (支持输入邮箱、邮箱关键词或序号)')
111
114
  .option('--no-restart', '换号后不自动唤起 Cursor')
115
+ .option('--no-upgrade', '跳过切号前 Refresh Token 自动续期')
116
+ .option('--reset-system-id', '同时尝试重置 Windows 注册表 MachineGuid (需管理员权限)')
117
+ .option('-f, --force', '跳过过期或过时 web Token 前置拦截,强行写入本地配置')
112
118
  .action(async (identifier, options) => {
113
119
  const store = new AccountStore();
114
120
  let targetAcc = store.getByIndexOrEmail(identifier);
121
+ let pastedTokenInput = false;
115
122
  if (!targetAcc) {
116
123
  const parsed = TokenParser.parse(identifier);
117
124
  if (parsed.isValid) {
118
- console.log(chalk.cyan('\n检测到直接传入了 Token 凭据,正在同步并极速换号...'));
125
+ pastedTokenInput = true;
126
+ console.log(chalk.cyan('\n检测到直接传入了 Token 凭据,正在预检并同步账号信息...'));
119
127
  let email = parsed.email;
120
128
  if (!email) {
121
129
  try {
@@ -126,19 +134,18 @@ export function createCli() {
126
134
  if (!email) {
127
135
  email = parsed.sub ? `${parsed.sub.replace('auth0|', '')}@cursor.sh` : `account_${Date.now().toString().slice(-6)}@cursor.sh`;
128
136
  }
137
+ const existing = store.getByEmail(email);
129
138
  const usageRes = await OfficialApiClient.fetchUsage(parsed.token);
130
- const subType = usageRes.success && usageRes.subscriptionType ? usageRes.subscriptionType : 'free';
131
- const machineIds = generateMachineIds();
132
- targetAcc = {
139
+ const machineIds = existing?.machine_ids || generateMachineIds();
140
+ targetAcc = applyParsedCredentialToAccount({
141
+ parsed,
133
142
  email,
134
- token: parsed.token,
135
- workos_cursor_session_token: parsed.workosSessionToken || parsed.token,
136
- subscription_type: subType,
137
- current_period_usage: usageRes.currentPeriodUsage,
138
- machine_ids: machineIds,
139
- };
140
- store.addOrUpdate(targetAcc);
141
- await copyToClipboard(targetAcc.token);
143
+ existing,
144
+ usageRes,
145
+ machineIds,
146
+ fallbackWorkosToToken: true,
147
+ });
148
+ printFactualTokenStatus(targetAcc.token, targetAcc.refresh_token, targetAcc.workos_cursor_session_token);
142
149
  }
143
150
  else {
144
151
  console.log(chalk.red(`\n未找到匹配账号或有效 Token: "${identifier}",请使用 cswitch list 查看当前账号列表。\n`));
@@ -149,33 +156,74 @@ export function createCli() {
149
156
  const storage = new StorageBridge(paths.storageJson);
150
157
  const sqlite = new SqliteBridge(paths.sqliteDb);
151
158
  console.log(chalk.cyan(`\n正在执行换号流程,目标: ${chalk.bold.white(targetAcc.email)} ...`));
152
- if (ProcessManager.isCursorRunning()) {
153
- console.log(chalk.grey('✔ [1/4] 检测到 Cursor 运行中 -> 发送退出信号,释放 SQLite 独占锁'));
154
- await ProcessManager.closeCursor();
159
+ const switchRes = await executeAccountSwitch({
160
+ store,
161
+ storage,
162
+ sqlite,
163
+ paths,
164
+ targetAccount: targetAcc,
165
+ autoUpgradeWebToken: options.upgrade !== false,
166
+ autoRefreshExpiring: options.upgrade !== false,
167
+ resetSystemRegistry: Boolean(options.resetSystemId),
168
+ resolveStaleTokenAction: (issue, acc) => resolveStaleSwitchWithHealing(issue, acc, {
169
+ store,
170
+ storage,
171
+ sqlite,
172
+ force: Boolean(options.force),
173
+ interactive: Boolean(process.stdin.isTTY),
174
+ }),
175
+ onStep: (step, detail) => {
176
+ if (step === 'resolve') {
177
+ console.log(chalk.grey('✔ [0/4] 校验凭据形态与 OAuth 续期链路...'));
178
+ }
179
+ else if (step === 'close' && detail === 'running') {
180
+ console.log(chalk.grey('✔ [1/4] 检测到 Cursor 运行中 -> 发送退出信号,释放 SQLite 独占锁'));
181
+ }
182
+ else if (step === 'backup') {
183
+ console.log(chalk.grey('✔ [2/4] 创建本地安全快照备份'));
184
+ }
185
+ },
186
+ });
187
+ if (switchRes.aborted) {
188
+ process.exitCode = 1;
189
+ return;
155
190
  }
156
- storage.createBackup();
157
- sqlite.createBackup();
158
- console.log(chalk.grey('✔ [2/4] 创建本地安全快照备份'));
159
- const machineIds = targetAcc.machine_ids || generateMachineIds();
160
- storage.writeMachineIds(machineIds);
161
- console.log(chalk.grey(`✔ [3/4] 换载该账号专属机器指纹: ${formatMachineIdSummary(machineIds)}`));
162
- const cleanToken = TokenParser.extractTokenPart(targetAcc.token);
163
- const refreshToken = targetAcc.workos_cursor_session_token || cleanToken;
164
- storage.writeAuth(targetAcc.email, cleanToken, refreshToken);
165
- await sqlite.injectAuth(targetAcc.email, cleanToken, refreshToken);
166
- store.markCurrent(targetAcc.email);
167
- console.log(chalk.grey('✔ [4/4] 原子注入认证凭据到 SQLite 数据库'));
168
- console.log(chalk.green(`\n✔ 换号成功!当前已激活: ${chalk.bold.white(targetAcc.email)}\n`));
191
+ const finalAcc = switchRes.account;
192
+ if (pastedTokenInput) {
193
+ if (finalAcc.email === targetAcc.email && finalAcc.token === targetAcc.token) {
194
+ store.addOrUpdate({ ...finalAcc, is_current: true });
195
+ }
196
+ await copyPreferredAccountCredential(finalAcc);
197
+ }
198
+ if (switchRes.refreshed) {
199
+ console.log(chalk.green('✔ 已自动完成 OAuth Refresh Token 无感续期'));
200
+ }
201
+ console.log(chalk.grey(`✔ [3/4] 换载该账号专属机器指纹 (JSON + SQLite + machineid): ${formatMachineIdSummary(switchRes.machineIds)}`));
202
+ if (switchRes.sidecarReport.authJsonUpdated || switchRes.sidecarReport.cliConfigUpdated) {
203
+ console.log(chalk.grey('✔ 已同步清理/更新 auth.json 与 cli-config.json 侧车凭据'));
204
+ }
205
+ if (switchRes.systemRegistryResult && !switchRes.systemRegistryResult.skipped) {
206
+ if (switchRes.systemRegistryResult.ok) {
207
+ console.log(chalk.green('✔ 已同步重置系统级 MachineGuid(原值已自动备份)'));
208
+ }
209
+ else if (switchRes.systemRegistryResult.error) {
210
+ console.log(chalk.yellow(`! 系统注册表提示: ${switchRes.systemRegistryResult.error}`));
211
+ }
212
+ }
213
+ for (const warn of switchRes.warnings) {
214
+ console.log(chalk.yellow(`! 提示: ${warn}`));
215
+ }
216
+ console.log(chalk.grey('✔ [4/4] 已清旧并原子注入认证凭据到 SQLite 数据库'));
217
+ console.log(chalk.green(`\n✔ 换号成功!当前已激活: ${chalk.bold.white(finalAcc.email)}\n`));
169
218
  if (options.restart !== false && paths.executablePath) {
170
219
  ProcessManager.launchCursor(paths.executablePath);
171
220
  console.log(chalk.green('✔ Cursor 已在后台启动\n'));
172
221
  }
173
222
  });
174
- // 4. add
175
223
  program
176
224
  .command('add [token]')
177
225
  .description('添加 Cursor 账号 (支持直接粘贴 user_xxx::eyJ... / eyJ...、纯净代登或浏览器登录)')
178
- .option('-p, --pure', '使用海外 S 级纯净住宅 IP 自动代登并提取 Token')
226
+ .option('-p, --pure', '使用云端纯净代登自动协助登录并提取 Token')
179
227
  .option('-b, --browser', '通过浏览器 OAuth 登录并自动截获授权凭据')
180
228
  .option('-e, --email <email>', '指定邮箱')
181
229
  .action(async (rawToken, options) => {
@@ -207,44 +255,54 @@ export function createCli() {
207
255
  }
208
256
  if (!rawToken) {
209
257
  console.log(chalk.yellow('\n请提供 Token 或使用选项,例:'));
210
- console.log(chalk.grey(' cswitch add --pure # 海外纯净住宅 IP 自动代登'));
211
- console.log(chalk.grey(' cswitch add --browser # 系统浏览器辅助录入'));
212
- console.log(chalk.grey(' cswitch add "user_xxx::eyJ..." # 直接粘贴 Token\n'));
258
+ console.log(chalk.grey(' cswitch add --pure # 云端纯净代登协助登录'));
259
+ console.log(chalk.grey(' cswitch add --browser # 系统浏览器辅助录入'));
260
+ console.log(chalk.grey(' cswitch add "user_xxx::eyJ..." # 粘贴一段 Token'));
261
+ console.log(chalk.grey(' cswitch add "eyJ...----rt...----user_xxx::eyJ..." # 粘贴三段完整凭据\n'));
262
+ process.exitCode = 1;
213
263
  return;
214
264
  }
215
265
  const parsed = TokenParser.parse(rawToken);
216
266
  if (!parsed.isValid) {
217
- console.log(chalk.red('\n未识别到有效的 Token 格式,仅支持 user_xxx::eyJ... 或 eyJ... 格式。\n'));
267
+ console.log(chalk.red('\n未识别到有效的 Token 格式,支持一段 (user_xxx::eyJ... / eyJ...) 或三段 (Access----Refresh----Web)。\n'));
268
+ process.exitCode = 1;
218
269
  return;
219
270
  }
220
271
  const fallbackEmail = parsed.sub ? `${parsed.sub.replace('auth0|', '')}@cursor.sh` : `account_${Date.now().toString().slice(-6)}@cursor.sh`;
221
272
  const email = options?.email || parsed.email || fallbackEmail;
222
- store.addOrUpdate({
273
+ printFactualTokenStatus(parsed.token, parsed.refreshToken, parsed.workosSessionToken);
274
+ const ingestRes = await upgradeAccountWebTokenOnIngest({
223
275
  email,
224
276
  token: parsed.token,
277
+ refresh_token: parsed.refreshToken,
225
278
  workos_cursor_session_token: parsed.workosSessionToken,
226
279
  });
227
- console.log(chalk.green(`\n✔ 录入成功!账号 ${chalk.bold.white(email)} 已加入本地库。\n`));
280
+ store.addOrUpdate(ingestRes.account);
281
+ printIngestUpgradeResult(ingestRes);
282
+ console.log(chalk.green(`\n✔ 录入成功!账号 ${chalk.bold.white(email)} 已加入本地库(${TokenParser.formatCredentialBadge(ingestRes.classification)})。\n`));
228
283
  });
229
- // 4.1 pure (纯净云端代登直达命令)
230
284
  program
231
285
  .command('pure [account]')
232
286
  .alias('cloud-login')
233
- .description('基于海外 S 级纯净住宅 IP 自动代登 Cursor,自动收发验证码并秒提官方 Token 入库')
234
- .action(async () => {
287
+ .description('通过云端代理辅助登录 Cursor,收发邮箱验证码并获取官方 Token 入库')
288
+ .action(async (account) => {
235
289
  const paths = resolveCursorPaths();
236
290
  const storage = new StorageBridge(paths.storageJson);
237
291
  const sqlite = new SqliteBridge(paths.sqliteDb);
238
292
  const store = new AccountStore();
239
293
  const pureService = new PureLoginService();
240
- await pureService.runInteractiveFlow(store, storage, sqlite, paths.executablePath);
294
+ await pureService.runInteractiveFlow(store, storage, sqlite, paths.executablePath, {
295
+ prefilledInput: account,
296
+ });
241
297
  });
242
- // 4.2 oauth (全新无痕浏览器官方 OAuth 网页登录)
243
298
  program
244
299
  .command('oauth')
245
300
  .alias('browser-login')
246
- .description('调起全新独立无痕/隐私浏览器进行 Cursor 官方网页 OAuth 登录,并全自动纳管入库')
247
- .action(async () => {
301
+ .description('调起全新独立无痕/隐私浏览器进行 Cursor 官方网页 OAuth 登录,并自动纳管入库')
302
+ .option('-f, --format <format>', '自动复制到剪贴板的格式: single(1·一段) / triple(3·三段包)')
303
+ .option('-3, --triple', '登录成功后自动复制三段完整凭据 (Access----Refresh----Web)')
304
+ .option('--show', '额外在终端输出完整凭据明文')
305
+ .action(async (options) => {
248
306
  const paths = resolveCursorPaths();
249
307
  const storage = new StorageBridge(paths.storageJson);
250
308
  const sqlite = new SqliteBridge(paths.sqliteDb);
@@ -267,118 +325,122 @@ export function createCli() {
267
325
  });
268
326
  email = inputEmail || fallback;
269
327
  }
270
- const machineIds = generateMachineIds();
271
328
  console.log(chalk.grey('\n正在向 Cursor 官方同步用量与订阅计划...'));
272
329
  const usageRes = await OfficialApiClient.fetchUsage(result.accessToken);
273
330
  const existing = store.getByEmail(email);
274
- const subType = usageRes.success && usageRes.subscriptionType
275
- ? usageRes.subscriptionType
276
- : existing?.subscription_type || 'free';
277
- const newAccount = {
331
+ const machineIds = existing?.machine_ids || generateMachineIds();
332
+ const newAccount = buildOAuthAccountInfo({
278
333
  email,
279
- token: result.accessToken,
280
- workos_cursor_session_token: result.refreshToken || result.accessToken,
281
- subscription_type: subType,
282
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
283
- machine_ids: machineIds,
284
- };
334
+ accessToken: result.accessToken,
335
+ refreshToken: result.refreshToken,
336
+ authId: result.authId,
337
+ usageRes,
338
+ existing,
339
+ machineIds,
340
+ });
285
341
  store.addOrUpdate(newAccount);
286
- const copied = await copyToClipboard(newAccount.token);
287
- console.log(boxen([
288
- chalk.bold.green('🎉 官方 OAuth 登录成功!账号已自动收录入库'),
289
- chalk.dim('────────────────────────────────────────────────'),
290
- ` 登录邮箱 : ${chalk.bold.white(newAccount.email)}`,
291
- ` 会员级别 : ${formatPlanBadge(newAccount.subscription_type)}`,
292
- ` 专属指纹 : ${chalk.cyan(formatMachineIdSummary(machineIds))} ${chalk.dim('(独立隔离防封)')}`,
293
- ` 官方凭据 : ${chalk.grey(newAccount.token.slice(0, 16))}...[已加密归档]`,
294
- ` 系统剪贴板: ${copied ? chalk.green('✔ Token 已自动复制到系统剪贴板 (可直接粘贴)') : chalk.yellow('○ 请手动复制')}`,
295
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
296
- console.log(chalk.grey(`\n提示: 可随时使用 cswitch use ${newAccount.email} 切换到该账号。\n`));
342
+ const copyFormat = normalizeCopyFormatInput(options?.format) || (options?.triple ? 'triple' : undefined);
343
+ await printExtractedCredentialsResult({
344
+ header: '🎉 官方 OAuth 登录成功!账号已自动收录入库',
345
+ account: newAccount,
346
+ machineIds,
347
+ copyFormat,
348
+ showPlaintext: Boolean(options?.show),
349
+ });
350
+ console.log(chalk.grey(`提示: 可随时使用 cswitch use ${newAccount.email} 切换到该账号。\n`));
297
351
  });
298
- // 4.2 token
299
352
  program
300
353
  .command('token [inputToken]')
301
354
  .alias('browser-token')
302
- .description('提取或录入官方 Token (若本机已登则自动秒提复制,未登调起无痕浏览器 OAuth 登录)')
303
- .action(async (inputToken) => {
355
+ .description('提取或录入官方 Token (支持一段或三段;若本机已登自动读取复制,未登调起无痕 OAuth 登录)')
356
+ .option('-f, --format <format>', '自动复制到剪贴板的格式: single(1·一段) / triple(3·三段包)')
357
+ .option('-3, --triple', '提取后自动复制三段完整凭据 (Access----Refresh----Web)')
358
+ .option('--show', '额外在终端输出完整凭据明文')
359
+ .action(async (inputToken, options) => {
304
360
  const paths = resolveCursorPaths();
305
361
  const storage = new StorageBridge(paths.storageJson);
306
362
  const sqlite = new SqliteBridge(paths.sqliteDb);
307
363
  const store = new AccountStore();
308
- // 如果命令行直接提供了 Token 参数
364
+ const copyFormat = normalizeCopyFormatInput(options?.format) || (options?.triple ? 'triple' : undefined);
309
365
  if (inputToken && inputToken.trim()) {
310
366
  const rawToken = inputToken.trim();
311
367
  const parsed = TokenParser.parse(rawToken);
312
368
  if (!parsed.isValid) {
313
- console.log(chalk.red('\n未识别到有效的 Token 格式,仅支持 user_xxx:: 或 eyJ... 格式。\n'));
369
+ console.log(chalk.red('\n未识别到有效的 Token 格式,支持一段 (user_xxx::eyJ... / eyJ...) 或三段 (Access----Refresh----Web)。\n'));
370
+ process.exitCode = 1;
314
371
  return;
315
372
  }
316
- const machineIds = generateMachineIds();
317
373
  console.log(chalk.grey('\n正在同步官方用量与订阅计划...'));
318
374
  const usageRes = await OfficialApiClient.fetchUsage(parsed.token);
319
375
  const fallbackEmail = parsed.sub ? `${parsed.sub.replace('auth0|', '')}@cursor.sh` : `account_${Date.now().toString().slice(-6)}@cursor.sh`;
320
376
  const email = parsed.email || fallbackEmail;
321
377
  const existing = store.getByEmail(email);
322
- const newAccount = {
378
+ const machineIds = existing?.machine_ids || generateMachineIds();
379
+ const draftAccount = applyParsedCredentialToAccount({
380
+ parsed,
323
381
  email,
324
- token: rawToken,
325
- workos_cursor_session_token: parsed.workosSessionToken || rawToken,
326
- subscription_type: usageRes.success && usageRes.subscriptionType ? usageRes.subscriptionType : (existing?.subscription_type || 'free'),
327
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
328
- machine_ids: machineIds,
329
- };
382
+ existing,
383
+ usageRes,
384
+ machineIds,
385
+ fallbackWorkosToToken: true,
386
+ });
387
+ printFactualTokenStatus(draftAccount.token, draftAccount.refresh_token, draftAccount.workos_cursor_session_token);
388
+ const ingestRes = await upgradeAccountWebTokenOnIngest(draftAccount);
389
+ const newAccount = ingestRes.account;
330
390
  store.addOrUpdate(newAccount);
331
- const copied = await copyToClipboard(newAccount.token);
332
- console.log(boxen([
333
- chalk.bold.green('✔ 账号 Token 录入成功!已加入本地多账号库'),
334
- chalk.dim('────────────────────────────────────────────────'),
335
- ` 登录邮箱 : ${chalk.bold.white(newAccount.email)}`,
336
- ` 会员级别 : ${formatPlanBadge(newAccount.subscription_type)}`,
337
- ` 专属指纹 : ${chalk.cyan(formatMachineIdSummary(machineIds))}`,
338
- ` 官方凭据 : ${chalk.grey(rawToken.slice(0, 16))}...[已加密保护]`,
339
- ` 系统剪贴板: ${copied ? chalk.green('✔ Token 已自动复制到系统剪贴板 (可直接 Ctrl+V 粘贴)') : chalk.yellow('○ 请手动复制')}`,
340
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
341
- console.log(chalk.grey(`\n提示: 可随时使用 cswitch use ${newAccount.email} 切换到该账号。\n`));
391
+ printIngestUpgradeResult(ingestRes);
392
+ await printExtractedCredentialsResult({
393
+ header: '✔ 账号 Token 录入成功!已加入本地多账号库',
394
+ account: newAccount,
395
+ machineIds,
396
+ copyFormat,
397
+ showPlaintext: Boolean(options?.show),
398
+ });
399
+ console.log(chalk.grey(`提示: 可随时使用 cswitch use ${newAccount.email} 切换到该账号。\n`));
342
400
  return;
343
401
  }
344
- // 1. 优先智能探测本机已登录态 (0 秒直提,免开浏览器)
345
- const localEmail = storage.readCurrentEmail() || (await sqlite.readEmail());
346
- const localToken = storage.readCurrentToken() || (await sqlite.readToken());
402
+ const localAuth = await readLocalCursorAuth(storage, sqlite);
403
+ const localEmail = localAuth.email;
404
+ const localToken = localAuth.token;
405
+ if (!localToken && localAuth.isEncrypted && localAuth.encryptionError) {
406
+ console.log(chalk.yellow(`\n! 本地检测到新版 safeStorage 加密凭据但解密失败: ${localAuth.encryptionError}`));
407
+ }
347
408
  if (localEmail && localToken) {
348
409
  console.log(chalk.cyan(`\n✔ 智能检测到本机 Cursor 已登录有效账号: ${chalk.bold.white(localEmail)}`));
349
410
  console.log(chalk.grey('正在同步官方用量与订阅计划...'));
350
411
  const existing = store.getByEmail(localEmail);
351
412
  const usageRes = await OfficialApiClient.fetchUsage(localToken);
352
- const machineIds = storage.readMachineIds() || existing?.machine_ids || generateMachineIds();
413
+ const diskIds = storage.readMachineIds();
414
+ const machineIds = diskIds['telemetry.devDeviceId']
415
+ ? diskIds
416
+ : existing?.machine_ids || generateMachineIds();
353
417
  const account = {
354
418
  email: localEmail,
355
419
  token: localToken,
420
+ refresh_token: localAuth.refreshToken || existing?.refresh_token,
421
+ workos_cursor_session_token: existing?.workos_cursor_session_token,
356
422
  subscription_type: usageRes.success && usageRes.subscriptionType ? usageRes.subscriptionType : (existing?.subscription_type || 'free'),
357
423
  current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
358
424
  machine_ids: machineIds,
359
425
  is_current: true,
360
426
  };
361
427
  store.addOrUpdate(account);
362
- const parsed = TokenParser.parse(localToken);
363
- const jwtToken = parsed.token || localToken;
364
- const copied = await copyToClipboard(jwtToken);
365
- console.log(boxen([
366
- chalk.bold.green('✔ 本机账号提取成功!已直接纳入本地库 (免开浏览器)'),
367
- chalk.dim('────────────────────────────────────────────────'),
368
- ` 登录邮箱 : ${chalk.bold.white(account.email)}`,
369
- ` 会员级别 : ${formatPlanBadge(account.subscription_type)}`,
370
- ` 专属指纹 : ${chalk.cyan(formatMachineIdSummary(machineIds))}`,
371
- ` 系统剪贴板: ${copied ? chalk.green('✔ Token 已自动复制到系统剪贴板 (可直接 Ctrl+V 粘贴)') : chalk.yellow('○ 请手动复制')}`,
372
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
428
+ await printExtractedCredentialsResult({
429
+ header: '✔ 本机账号提取成功!已直接纳入本地库 (免开浏览器)',
430
+ account,
431
+ machineIds,
432
+ copyFormat,
433
+ showPlaintext: Boolean(options?.show),
434
+ });
373
435
  return;
374
436
  }
375
- // 2. 本机未登录,调起全新无痕浏览器执行官方 OAuth 登录
376
437
  console.log(chalk.cyan('\n⚡ 本机未检测到登录态,正在调起无痕浏览器执行官方 OAuth 登录...\n'));
377
438
  const oauthRes = await OAuthReceiver.startOfficialOAuthFlow();
378
439
  if (!oauthRes.success || !oauthRes.accessToken) {
379
440
  if (oauthRes.message) {
380
441
  console.log(chalk.yellow(`\n${oauthRes.message}\n`));
381
442
  }
443
+ process.exitCode = 1;
382
444
  return;
383
445
  }
384
446
  let email = oauthRes.email;
@@ -392,86 +454,105 @@ export function createCli() {
392
454
  });
393
455
  email = inputEmail || fallback;
394
456
  }
395
- const machineIds = generateMachineIds();
396
457
  console.log(chalk.grey('\n正在向 Cursor 官方同步用量与订阅计划...'));
397
458
  const usageRes = await OfficialApiClient.fetchUsage(oauthRes.accessToken);
398
459
  const existing = store.getByEmail(email);
399
- const subType = usageRes.success && usageRes.subscriptionType
400
- ? usageRes.subscriptionType
401
- : existing?.subscription_type || 'free';
402
- const newAccount = {
460
+ const machineIds = existing?.machine_ids || generateMachineIds();
461
+ const newAccount = buildOAuthAccountInfo({
403
462
  email,
404
- token: oauthRes.accessToken,
405
- workos_cursor_session_token: oauthRes.refreshToken || oauthRes.accessToken,
406
- subscription_type: subType,
407
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
408
- machine_ids: machineIds,
409
- };
463
+ accessToken: oauthRes.accessToken,
464
+ refreshToken: oauthRes.refreshToken,
465
+ authId: oauthRes.authId,
466
+ usageRes,
467
+ existing,
468
+ machineIds,
469
+ });
410
470
  store.addOrUpdate(newAccount);
411
- const copied = await copyToClipboard(newAccount.token);
412
- console.log(boxen([
413
- chalk.bold.green('🎉 官方 OAuth 登录成功!账号已自动收录入库'),
414
- chalk.dim('────────────────────────────────────────────────'),
415
- ` 登录邮箱 : ${chalk.bold.white(newAccount.email)}`,
416
- ` 会员级别 : ${formatPlanBadge(newAccount.subscription_type)}`,
417
- ` 专属指纹 : ${chalk.cyan(formatMachineIdSummary(machineIds))} ${chalk.dim('(独立隔离防封)')}`,
418
- ` 官方凭据 : ${chalk.grey(newAccount.token.slice(0, 16))}...[已加密归档]`,
419
- ` 系统剪贴板: ${copied ? chalk.green('✔ Token 已自动复制到系统剪贴板 (可直接粘贴)') : chalk.yellow('○ 请手动复制')}`,
420
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
421
- console.log(chalk.grey(`\n提示: 可随时使用 cswitch use ${newAccount.email} 切换到该账号。\n`));
471
+ await printExtractedCredentialsResult({
472
+ header: '🎉 官方 OAuth 登录成功!账号已自动收录入库',
473
+ account: newAccount,
474
+ machineIds,
475
+ copyFormat,
476
+ showPlaintext: Boolean(options?.show),
477
+ });
478
+ console.log(chalk.grey(`提示: 可随时使用 cswitch use ${newAccount.email} 切换到该账号。\n`));
422
479
  });
423
- // 4.3 copy (一键拷贝指定账号或当前在用账号 Token 到剪贴板)
424
480
  program
425
- .command('copy [email]')
481
+ .command('copy [identifier]')
426
482
  .alias('cp')
427
- .description('一键复制指定账号或当前在用账号的 Token 到系统剪贴板')
428
- .action(async (targetEmail) => {
483
+ .description('一键复制指定账号或当前在用账号的 Token(支持一段单凭据或三段完整包)到系统剪贴板')
484
+ .option('-f, --format <format>', '复制格式: single(1·一段) / triple(3·三段包) / web(网页Cookie) / json')
485
+ .option('-3, --triple', '一键复制三段完整凭据 (Access----Refresh----Web)')
486
+ .option('-i, --interactive', '打开交互式选择菜单(可选一段 / 三段 / 切换默认复制偏好)')
487
+ .action(async (identifier, options) => {
429
488
  const paths = resolveCursorPaths();
430
489
  const storage = new StorageBridge(paths.storageJson);
431
490
  const sqlite = new SqliteBridge(paths.sqliteDb);
432
491
  const store = new AccountStore();
433
- let email = targetEmail;
434
- let tokenToCopy = '';
435
- if (email) {
436
- const acc = store.getByEmail(email);
492
+ let targetAcc;
493
+ if (identifier) {
494
+ const acc = store.getByIndexOrEmail(identifier);
437
495
  if (!acc) {
438
- console.log(chalk.red(`\n未在本地库中找到邮箱为 ${email} 的账号\n`));
496
+ console.log(chalk.red(`\n未在本地库中找到匹配账号: "${identifier}"\n`));
497
+ process.exitCode = 1;
439
498
  return;
440
499
  }
441
- tokenToCopy = acc.token;
500
+ targetAcc = acc;
442
501
  }
443
502
  else {
444
- tokenToCopy = storage.readCurrentToken() || (await sqlite.readToken()) || '';
445
- email = storage.readCurrentEmail() || (await sqlite.readEmail()) || '当前账号';
446
- if (!tokenToCopy) {
447
- const currentAcc = store.getCurrentAccount();
448
- if (currentAcc) {
449
- tokenToCopy = currentAcc.token;
450
- email = currentAcc.email;
451
- }
503
+ const localAuth = await readLocalCursorAuth(storage, sqlite);
504
+ if (!localAuth.token && localAuth.isEncrypted && localAuth.encryptionError) {
505
+ console.log(chalk.yellow(`\n! 本地凭据为 safeStorage 密文且无法解密: ${localAuth.encryptionError}`));
506
+ }
507
+ const currentAcc = (localAuth.email ? store.getByEmail(localAuth.email) : undefined) || store.getCurrentAccount();
508
+ if (localAuth.token) {
509
+ targetAcc = {
510
+ ...(currentAcc || { email: localAuth.email || '当前账号', token: localAuth.token }),
511
+ email: localAuth.email || currentAcc?.email || '当前账号',
512
+ token: localAuth.token,
513
+ refresh_token: localAuth.refreshToken || currentAcc?.refresh_token,
514
+ workos_cursor_session_token: currentAcc?.workos_cursor_session_token,
515
+ machine_ids: currentAcc?.machine_ids,
516
+ };
517
+ }
518
+ else if (currentAcc) {
519
+ targetAcc = currentAcc;
452
520
  }
453
521
  }
454
- if (!tokenToCopy) {
522
+ if (!targetAcc || !targetAcc.token) {
455
523
  console.log(chalk.yellow('\n未检测到有效 Token,请先登录或使用 cswitch token 进行提取。\n'));
524
+ process.exitCode = 1;
525
+ return;
526
+ }
527
+ if (options?.interactive) {
528
+ await runInteractiveCopyAccountMenu(targetAcc);
529
+ return;
530
+ }
531
+ const rawFmt = options?.triple ? 'triple' : options?.format;
532
+ const requestedFmt = normalizeCopyFormatInput(rawFmt);
533
+ if (rawFmt && !requestedFmt) {
534
+ console.log(chalk.red(`\n不支持的复制格式 "${rawFmt}",可选值: single(1)、triple(3)、web、json。\n`));
535
+ process.exitCode = 1;
456
536
  return;
457
537
  }
458
- const parsed = TokenParser.parse(tokenToCopy);
459
- const jwtToken = parsed.token || tokenToCopy;
460
- const success = await copyToClipboard(jwtToken);
538
+ const copyRes = await copyPreferredAccountCredential(targetAcc, {
539
+ format: requestedFmt,
540
+ });
461
541
  console.log(boxen([
462
542
  chalk.bold.green('✔ Token 已成功复制到系统剪贴板!'),
463
543
  chalk.dim('────────────────────────────────────────────────'),
464
- ` 账号邮箱 : ${chalk.bold.white(email)}`,
465
- ` 凭据类型 : ${chalk.cyan('原生 Bearer JWT (Access Token)')}`,
466
- ` 凭据预览 : ${chalk.dim(jwtToken.slice(0, 16))}...${chalk.dim(jwtToken.slice(-12))} ${chalk.grey(`(共 ${jwtToken.length} 字符)`)}`,
467
- ` 操作提示 : ${chalk.yellow('直接使用 Ctrl + V (或 Cmd + V) 粘贴即可')}`,
544
+ ` 账号邮箱 : ${chalk.bold.white(targetAcc.email)}`,
545
+ ...renderCredentialSummaryLines(copyRes.bundles, copyRes.resolvedFormat),
546
+ ` 操作提示 : ${chalk.yellow('直接使用 Ctrl + V (或 Cmd + V) 粘贴即可(加 -3 可复制三段包,加 -i 可交互选择)')}`,
468
547
  ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
469
- if (!success) {
470
- console.log(chalk.yellow('提示: 自动写入剪贴板未生效,以下为 Token 明文,可手动选中复制:'));
471
- console.log(chalk.grey(jwtToken) + '\n');
548
+ if (copyRes.fallbackReason) {
549
+ console.log(chalk.yellow(`! 提示: ${copyRes.fallbackReason}\n`));
550
+ }
551
+ if (!copyRes.copied) {
552
+ console.log(chalk.yellow('提示: 自动写入剪贴板未生效,以下为凭据明文,可手动选中复制:'));
553
+ console.log(chalk.grey(copyRes.text) + '\n');
472
554
  }
473
555
  });
474
- // 5. capture
475
556
  program
476
557
  .command('capture [alias]')
477
558
  .description('一键收录当前电脑 Cursor IDE 正在登录的有效账号')
@@ -480,16 +561,23 @@ export function createCli() {
480
561
  const storage = new StorageBridge(paths.storageJson);
481
562
  const sqlite = new SqliteBridge(paths.sqliteDb);
482
563
  const store = new AccountStore();
483
- const email = storage.readCurrentEmail() || (await sqlite.readEmail());
484
- const token = storage.readCurrentToken() || (await sqlite.readToken());
564
+ const localAuth = await readLocalCursorAuth(storage, sqlite);
565
+ const email = localAuth.email;
566
+ const token = localAuth.token;
485
567
  if (!email || !token) {
486
- console.log(chalk.yellow('\n未能从本地 Cursor 发现登录数据,请确认 Cursor 已登录。\n'));
568
+ if (localAuth.isEncrypted && !token) {
569
+ console.log(chalk.yellow(`\n! 检测到新版 safeStorage 加密凭据但无法在本环境解密: ${localAuth.encryptionError || '未知错误'}\n`));
570
+ }
571
+ else {
572
+ console.log(chalk.yellow('\n未能从本地 Cursor 发现登录数据,请确认 Cursor 已登录。\n'));
573
+ }
487
574
  return;
488
575
  }
489
576
  const machineIds = storage.readMachineIds();
490
577
  store.addOrUpdate({
491
578
  email,
492
579
  token,
580
+ refresh_token: localAuth.refreshToken || undefined,
493
581
  username: alias || null,
494
582
  machine_ids: machineIds,
495
583
  is_current: true,
@@ -497,7 +585,6 @@ export function createCli() {
497
585
  console.log(chalk.green(`\n✔ 成功收录本机在用账号: ${chalk.bold.white(email)}`));
498
586
  console.log(chalk.grey(`• 绑定硬件指纹: ${formatMachineIdSummary(machineIds)}\n`));
499
587
  });
500
- // 6. dash / dashboard
501
588
  program
502
589
  .command('dash [identifier]')
503
590
  .alias('dashboard')
@@ -505,14 +592,17 @@ export function createCli() {
505
592
  .option('-t, --token <token>', '直接指定 Token 凭据免密打开控制台')
506
593
  .action(async (identifier, options) => {
507
594
  if (options?.token) {
595
+ const parsedOpt = TokenParser.parse(options.token);
596
+ const tokenForDash = parsedOpt.isValid
597
+ ? parsedOpt.workosSessionToken || parsedOpt.token
598
+ : options.token;
508
599
  console.log(chalk.cyan('\n正在使用指定 Token 调起独立浏览器并免密直达 Cursor 控制台...'));
509
- await DashboardLauncher.openDashboardWithToken(options.token, identifier || 'Direct Token User');
600
+ await DashboardLauncher.openDashboardWithToken(tokenForDash, identifier || parsedOpt.email || 'Direct Token User');
510
601
  return;
511
602
  }
512
603
  const store = new AccountStore();
513
604
  let targetAcc = identifier ? store.getByIndexOrEmail(identifier) : store.loadAll().find((a) => a.is_current);
514
605
  if (!targetAcc && identifier) {
515
- // 尝试解析是否直接传入了 Token (user_xxx:: 或 eyJ...)
516
606
  const parsed = TokenParser.parse(identifier);
517
607
  if (parsed.isValid) {
518
608
  process.stdout.write(chalk.grey('\n正在解析 Token 并同步账号信息... '));
@@ -534,14 +624,14 @@ export function createCli() {
534
624
  const subType = usageRes.success && usageRes.subscriptionType
535
625
  ? usageRes.subscriptionType
536
626
  : existing?.subscription_type || 'free';
537
- targetAcc = {
627
+ targetAcc = applyParsedCredentialToAccount({
628
+ parsed,
538
629
  email,
539
- token: parsed.token,
540
- workos_cursor_session_token: parsed.workosSessionToken || parsed.token,
541
- subscription_type: subType,
542
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
543
- machine_ids: existing?.machine_ids || generateMachineIds(),
544
- };
630
+ existing,
631
+ usageRes,
632
+ machineIds: existing?.machine_ids || generateMachineIds(),
633
+ fallbackWorkosToToken: true,
634
+ });
545
635
  if (!existing) {
546
636
  store.addOrUpdate(targetAcc);
547
637
  console.log(chalk.grey('✔ 已自动纳管录入本地多账号库'));
@@ -561,11 +651,10 @@ export function createCli() {
561
651
  console.log(chalk.cyan(`\n正在调起全新独立浏览器并免密直达 Cursor 控制台 (${targetAcc.email})...`));
562
652
  await DashboardLauncher.openDashboard(targetAcc);
563
653
  });
564
- // 6.5 mail / outlook (打开独立浏览器自动登录 Outlook 邮箱)
565
654
  program
566
655
  .command('mail [identifier]')
567
656
  .alias('outlook')
568
- .description('打开全新的独立浏览器实例并自动登录 Outlook 邮箱 (遇辅助邮箱/安全验证自动停下交接)')
657
+ .description('打开独立浏览器自动登录 Outlook 邮箱')
569
658
  .option('-p, --password <pwd>', '指定邮箱密码 (不传则优先读取已保存密码或在网页手动输入)')
570
659
  .option('-d, --dash', '同时在打开的独立浏览器新标签页中免密直达 Cursor 官网控制台')
571
660
  .option('-t, --token <token>', '指定 Cursor Token 并在浏览器新标签页中免密直达控制台')
@@ -575,7 +664,6 @@ export function createCli() {
575
664
  let emailPassword = options?.password ? String(options.password).trim() : '';
576
665
  let cursorToken = options?.token ? String(options.token).trim() : '';
577
666
  if (identifier) {
578
- // 尝试按多段式解析 (支持 email----password 等格式)
579
667
  const pureLogin = new PureLoginService();
580
668
  const parsed = pureLogin.parseAccountString(identifier);
581
669
  if (parsed.email) {
@@ -585,7 +673,6 @@ export function createCli() {
585
673
  }
586
674
  }
587
675
  else {
588
- // 尝试从已有账号库匹配
589
676
  const targetAcc = store.getByIndexOrEmail(identifier);
590
677
  if (targetAcc) {
591
678
  email = targetAcc.email;
@@ -602,7 +689,6 @@ export function createCli() {
602
689
  }
603
690
  }
604
691
  else {
605
- // 未传 identifier,优先使用当前在用账号,或列表中第一个账号
606
692
  const currentAcc = store.loadAll().find((a) => a.is_current) || store.loadAll()[0];
607
693
  if (currentAcc) {
608
694
  email = currentAcc.email;
@@ -616,9 +702,9 @@ export function createCli() {
616
702
  }
617
703
  if (!email) {
618
704
  console.log(chalk.yellow('\n未检测到可用邮箱,请使用 "cswitch mail <email>" 或直接进入 cswitch 主菜单。\n'));
705
+ process.exitCode = 1;
619
706
  return;
620
707
  }
621
- // 若指定了 -d 但未指定 token,尝试从库中寻找匹配账号的 token
622
708
  if (options?.dash && !cursorToken) {
623
709
  const matched = store.getByEmail(email) || store.loadAll().find((a) => a.email.toLowerCase() === email.toLowerCase());
624
710
  if (matched?.token) {
@@ -628,7 +714,7 @@ export function createCli() {
628
714
  const shouldOpenDash = Boolean(options?.dash || (options?.token && cursorToken));
629
715
  console.log(chalk.cyan(`\n正在调起全新独立浏览器并自动登录 ${email}...`));
630
716
  if (shouldOpenDash && cursorToken) {
631
- console.log(chalk.green(` [联动] 同时在浏览器新标签页免密打开 Cursor 控制台 (Token: ${cursorToken.slice(0, 15)}...)`));
717
+ console.log(chalk.green(` [联动] 同时在浏览器新标签页免密打开 Cursor 控制台 (Token: ${maskToken(cursorToken)})`));
632
718
  }
633
719
  const res = await OutlookLauncher.openMailbox({
634
720
  email,
@@ -638,24 +724,22 @@ export function createCli() {
638
724
  });
639
725
  OutlookLauncher.printResultCard(res);
640
726
  });
641
- // 7. refund / aozai / seat (奥仔退款)
642
727
  program
643
728
  .command('refund [identifier]')
644
- .alias('aozai')
645
729
  .alias('seat')
646
- .description('奥仔退款:执行席位退款,账号退出并恢复为 Free 免费状态')
647
- .option('-c, --card <code>', '使用指定席位卡密 (不传则使用已保存卡密或提示输入)')
730
+ .description('Cursor 退款服务:使用卡密自助完成退款处理,账号退出席位并恢复为 Free 免费状态')
731
+ .option('-c, --card <code>', '使用指定退款卡密 (不传则使用已保存卡密或提示输入)')
648
732
  .option('-t, --token <token>', '直接指定 Cursor Session Token 执行退款')
649
733
  .option('-s, --status', '查询当前卡密剩余点数与扣点费率')
650
734
  .option('-u, --usage', '查看卡密历史使用与退款流水明细')
651
- .option('--set-card <code>', '保存默认席位卡密到本地配置')
652
- .option('--api-base <url>', '自定义奥仔退款服务 API 网关地址')
735
+ .option('--set-card <code>', '保存默认退款卡密到本地配置')
736
+ .option('--api-base <url>', '自定义 Cursor 退款服务 API 网关地址')
653
737
  .option('-y, --yes', '自动化免确认模式 (自动同意扣费与重启 Cursor)')
654
738
  .action(async (identifier, options) => {
655
739
  const refundService = new RefundService(options?.apiBase);
656
740
  if (options?.setCard) {
657
741
  refundService.getConfigStore().setSeatCardCode(options.setCard);
658
- console.log(chalk.green(`\n✔ 默认席位卡密已保存: ${options.setCard}\n`));
742
+ console.log(chalk.green(`\n✔ 默认退款卡密已保存: ${maskToken(options.setCard)}\n`));
659
743
  return;
660
744
  }
661
745
  if (options?.status) {
@@ -664,8 +748,8 @@ export function createCli() {
664
748
  return;
665
749
  const balRes = await refundService.getClient().getBalance(cardRes.auth.token);
666
750
  const b = balRes.data || cardRes.auth;
667
- console.log(chalk.bold.cyan('\n● 奥仔席位退款卡密状态:'));
668
- console.log(`• 卡密编号 : ${chalk.white(cardRes.cardCode)}`);
751
+ console.log(chalk.bold.cyan('\n● Cursor 退款服务卡密状态:'));
752
+ console.log(`• 卡密编号 : ${chalk.white(maskToken(cardRes.cardCode))}`);
669
753
  console.log(`• 剩余点数 : ${chalk.bold.green(b.remaining)} 点`);
670
754
  console.log(`• 已用点数 : ${chalk.yellow(b.used)} 点`);
671
755
  console.log(`• 单次扣点 : ${chalk.magenta(b.pointsPerOp)} 点`);
@@ -695,7 +779,85 @@ export function createCli() {
695
779
  autoYes: Boolean(options?.yes),
696
780
  });
697
781
  });
698
- // 8. id
782
+ program
783
+ .command('extract [identifier]')
784
+ .alias('link')
785
+ .alias('stripe')
786
+ .alias('tilian')
787
+ .description('Cursor 提取老套餐支付链接:需绑定提链卡密,生成官方付款直链 (Pro/Pro+/Ultra/Teams),出链成功才扣次')
788
+ .option('-t, --token <token>', '直接指定 Cursor Session Token 或多段式凭据提取')
789
+ .option('--tier <tier>', '订阅档位: pro ($20) / pro_plus ($60) / ultra ($200) / team ($40)', 'pro')
790
+ .option('-k, --card <code>', '使用指定【提取老套餐支付链接卡密】')
791
+ .option('--set-card <code>', '保存默认【提取老套餐支付链接卡密】到本地配置')
792
+ .option('-b, --batch', '批量扫描并为账号池内所有可用账号一键提链')
793
+ .option('--export <file>', '将提链结果导出为 JSON 文件')
794
+ .option('-c, --copy', '提取成功后自动复制支付直链到系统剪贴板')
795
+ .option('-o, --open', '提取成功后自动调起默认浏览器打开支付直链')
796
+ .option('-v, --verify <url>', '校验已有 Stripe Checkout 或 Portal 链接有效性与超时状态')
797
+ .option('--json', '以标准 JSON 格式输出结果')
798
+ .option('--api-base <url>', '自定义提链 API 网关')
799
+ .action(async (identifier, options) => {
800
+ const extractService = new ExtractService(options?.apiBase);
801
+ if (options?.setCard) {
802
+ const trimmedCard = String(options.setCard).trim();
803
+ const chk = await extractService.getClient().checkKey(trimmedCard);
804
+ const isExhausted = chk.max_uses !== undefined && chk.max_uses !== -1 && (chk.remaining ?? 0) <= 0;
805
+ if (!chk.valid || isExhausted) {
806
+ const reason = isExhausted ? '该卡密提取额度已用尽' : chk.detail || '卡密无效或类型不匹配';
807
+ if (options?.json) {
808
+ console.log(JSON.stringify({ ok: false, error: reason }, null, 2));
809
+ }
810
+ else {
811
+ console.log(chalk.red(`\n✖ 提取老套餐支付链接卡密校验失败 (${reason}),未覆盖本地配置。\n`));
812
+ }
813
+ process.exitCode = 1;
814
+ return;
815
+ }
816
+ extractService.getConfigStore().setExtractCardCode(trimmedCard);
817
+ if (options?.json) {
818
+ console.log(JSON.stringify({ ok: true, code: trimmedCard, remaining: chk.remaining }, null, 2));
819
+ }
820
+ else {
821
+ const remText = chk.remaining === -1 ? '无限次' : `${chk.remaining ?? '--'} 次`;
822
+ console.log(chalk.green(`\n✔ 默认提取老套餐支付链接卡密校验通过并已保存: ${maskToken(trimmedCard)} (剩余 ${remText})\n`));
823
+ }
824
+ return;
825
+ }
826
+ const tier = normalizeExtractTier(options?.tier);
827
+ if (options?.verify) {
828
+ await extractService.verifyLink(options.verify);
829
+ return;
830
+ }
831
+ if (options?.batch) {
832
+ await extractService.batchExtract({
833
+ tier,
834
+ cardCode: options?.card,
835
+ exportFile: options?.export,
836
+ });
837
+ return;
838
+ }
839
+ let targetAcc;
840
+ const store = new AccountStore();
841
+ if (identifier) {
842
+ targetAcc = store.getByIndexOrEmail(identifier);
843
+ if (!targetAcc) {
844
+ console.log(chalk.red(`\n未找到匹配账号: "${identifier}"\n`));
845
+ process.exit(1);
846
+ }
847
+ }
848
+ else if (!options?.token) {
849
+ targetAcc = store.loadAll().find((a) => a.is_current) || store.loadAll()[0];
850
+ }
851
+ await extractService.extractForAccount({
852
+ account: targetAcc,
853
+ token: options?.token,
854
+ tier,
855
+ cardCode: options?.card,
856
+ copy: Boolean(options?.copy),
857
+ open: Boolean(options?.open),
858
+ json: Boolean(options?.json),
859
+ });
860
+ });
699
861
  const idCmd = program.command('id').description('Cursor 机器硬件指纹 (Machine ID) 管理');
700
862
  idCmd
701
863
  .command('status')
@@ -712,16 +874,36 @@ export function createCli() {
712
874
  });
713
875
  idCmd
714
876
  .command('reset')
715
- .description('一键备份并重置全套崭新的随机机器码')
716
- .action(() => {
877
+ .description('一键备份并重置全套崭新的随机机器码 (同步写入 storage.json、state.vscdb 与 machineid)')
878
+ .option('--system', '同时尝试重置 Windows 注册表 MachineGuid (需管理员权限)')
879
+ .action(async (options) => {
717
880
  const paths = resolveCursorPaths();
718
881
  const storage = new StorageBridge(paths.storageJson);
882
+ const sqlite = new SqliteBridge(paths.sqliteDb);
719
883
  const newIds = generateMachineIds();
720
884
  storage.createBackup();
721
- storage.writeMachineIds(newIds);
722
- console.log(chalk.green('\n✔ 硬件指纹已重置为全新随机硬件码!旧指纹已安全备份。\n'));
885
+ sqlite.createBackup();
886
+ const applied = await applyMachineIdsToCursor({
887
+ storage,
888
+ sqlite,
889
+ paths,
890
+ machineIds: newIds,
891
+ resetSystemRegistry: Boolean(options.system),
892
+ });
893
+ console.log(chalk.green('\n✔ 硬件指纹已全链路重置为全新随机硬件码!旧指纹已安全备份。'));
894
+ if (applied.sidecarReport.machineIdFileUpdated) {
895
+ console.log(chalk.grey(`• 已同步更新 ${paths.machineIdFile}`));
896
+ }
897
+ if (applied.systemRegistryResult && !applied.systemRegistryResult.skipped) {
898
+ if (applied.systemRegistryResult.ok) {
899
+ console.log(chalk.green('• 已同步重置系统级 MachineGuid(原值已备份)'));
900
+ }
901
+ else if (applied.systemRegistryResult.error) {
902
+ console.log(chalk.yellow(`! 系统注册表提示: ${applied.systemRegistryResult.error}`));
903
+ }
904
+ }
905
+ console.log('');
723
906
  });
724
- // 8. remove / rm
725
907
  program
726
908
  .command('remove [identifier]')
727
909
  .alias('rm')
@@ -738,28 +920,37 @@ export function createCli() {
738
920
  const acc = store.getByIndexOrEmail(identifier);
739
921
  if (!acc) {
740
922
  console.log(chalk.red(`\n未找到匹配账号: "${identifier}"\n`));
923
+ process.exitCode = 1;
741
924
  return;
742
925
  }
743
926
  store.remove(acc.email);
744
927
  console.log(chalk.green(`\n✔ 账号 ${acc.email} 已成功移除。\n`));
745
928
  });
746
- // 9. import / export
747
929
  program
748
930
  .command('import <filePath>')
749
- .description('从文本或 JSON 文件批量导入账号')
931
+ .description('从文本 (支持 ---- 多段账号行与裸 Token) 或 JSON 文件批量导入账号')
750
932
  .action((filePath) => {
751
933
  if (!fs.existsSync(filePath)) {
752
934
  console.log(chalk.red(`\n文件不存在: ${filePath}\n`));
935
+ process.exitCode = 1;
753
936
  return;
754
937
  }
755
938
  const store = new AccountStore();
756
939
  const content = fs.readFileSync(filePath, 'utf8');
757
940
  let count = 0;
758
- if (filePath.endsWith('.json')) {
759
- const arr = JSON.parse(content);
941
+ if (filePath.toLowerCase().endsWith('.json')) {
942
+ let arr;
943
+ try {
944
+ arr = JSON.parse(content);
945
+ }
946
+ catch (err) {
947
+ console.log(chalk.red(`\nJSON 解析失败: ${err?.message || err}\n`));
948
+ process.exitCode = 1;
949
+ return;
950
+ }
760
951
  if (Array.isArray(arr)) {
761
952
  for (const item of arr) {
762
- if (item.email && item.token) {
953
+ if (item && item.email && (item.token || item.email_password)) {
763
954
  store.addOrUpdate(item);
764
955
  count++;
765
956
  }
@@ -767,18 +958,7 @@ export function createCli() {
767
958
  }
768
959
  }
769
960
  else {
770
- const lines = content.split('\n');
771
- for (const line of lines) {
772
- const parsed = TokenParser.parse(line);
773
- if (parsed.isValid && parsed.email) {
774
- store.addOrUpdate({
775
- email: parsed.email,
776
- token: parsed.token,
777
- workos_cursor_session_token: parsed.workosSessionToken,
778
- });
779
- count++;
780
- }
781
- }
961
+ count = importAccountsFromText(content, store);
782
962
  }
783
963
  console.log(chalk.green(`\n✔ 导入完成!共新增/更新 ${count} 个账号。\n`));
784
964
  });
@@ -789,10 +969,9 @@ export function createCli() {
789
969
  const store = new AccountStore();
790
970
  const accounts = store.loadAll();
791
971
  const outPath = targetPath || `cursor_accounts_backup_${Date.now()}.json`;
792
- fs.writeFileSync(outPath, JSON.stringify(accounts, null, 2), 'utf8');
972
+ writeSecureFileSync(outPath, JSON.stringify(accounts, null, 2));
793
973
  console.log(chalk.green.bold(`\n✔ 成功导出 ${accounts.length} 个账号至: ${outPath}\n`));
794
974
  });
795
- // 10. update / upgrade
796
975
  program
797
976
  .command('update')
798
977
  .alias('upgrade')