cursor-switch 1.0.7 → 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 (86) 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 -241
  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 +0 -20
  15. package/dist/core/dashboard-launcher.js +3 -53
  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 -31
  29. package/dist/core/outlook-launcher.js +194 -248
  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 +54 -38
  33. package/dist/core/pure-login-service.js +483 -395
  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 -548
  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
  85. package/dist/core/welcome-offer-service.d.ts +0 -52
  86. package/dist/core/welcome-offer-service.js +0 -369
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,29 +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
- import { WelcomeOfferService } from './core/welcome-offer-service.js';
27
28
  import { UpdateChecker, CURRENT_VERSION } from './core/update-checker.js';
29
+ import { importAccountsFromText } from './utils/account-text-importer.js';
28
30
  import boxen from 'boxen';
29
- import { copyToClipboard } from './utils/clipboard.js';
30
31
  import { safeInput } from './utils/prompt-utils.js';
32
+ import { ensureGlobalProxy } from './utils/proxy-bootstrap.js';
31
33
  export function createCli() {
34
+ ensureGlobalProxy();
32
35
  const program = new Command();
33
36
  program
34
37
  .name('cswitch')
35
38
  .description('Cursor IDE 极速、安全、纯本地运行的多账号与防封虚拟机器指纹管理工具')
36
39
  .version(CURRENT_VERSION)
37
40
  .action(async () => {
38
- // 无参数时默认进入交互式主菜单
39
41
  await runInteractiveMenu();
40
42
  });
41
- // 1. current / whoami
42
43
  program
43
44
  .command('current')
44
45
  .alias('whoami')
@@ -48,8 +49,9 @@ export function createCli() {
48
49
  const storage = new StorageBridge(paths.storageJson);
49
50
  const sqlite = new SqliteBridge(paths.sqliteDb);
50
51
  const store = new AccountStore();
51
- const email = storage.readCurrentEmail() || (await sqlite.readEmail()) || '未登录';
52
- const token = storage.readCurrentToken() || (await sqlite.readToken()) || '';
52
+ const localAuth = await readLocalCursorAuth(storage, sqlite);
53
+ const email = localAuth.email || '未登录';
54
+ const token = localAuth.token || '';
53
55
  const machineIds = storage.readMachineIds();
54
56
  const acc = store.getByEmail(email);
55
57
  const expiry = getExpiryStatus(acc?.current_period_usage?.billingCycleEnd);
@@ -57,11 +59,13 @@ export function createCli() {
57
59
  console.log(`• 登录邮箱 : ${chalk.bold.white(email)}`);
58
60
  console.log(`• 会员级别 : ${formatPlanBadge(acc?.subscription_type)}`);
59
61
  console.log(`• 具体到期 : ${chalk.blue(expiry.formattedDate)} (${expiry.countdownText})`);
60
- 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
+ }
61
66
  console.log(`• 机器指纹 : ${chalk.magenta(formatMachineIdSummary(machineIds))}`);
62
67
  console.log(`• Cursor进程 : ${ProcessManager.isCursorRunning() ? chalk.green('● 运行中') : chalk.grey('○ 未运行')}\n`);
63
68
  });
64
- // 2. list / ls
65
69
  program
66
70
  .command('list')
67
71
  .alias('ls')
@@ -93,7 +97,6 @@ export function createCli() {
93
97
  const limit = options.limit !== undefined ? Number(options.limit) : 20;
94
98
  let displayAccounts = accounts;
95
99
  if (limit > 0 && accounts.length > limit) {
96
- // 优先将当前在用的账号排在最前面
97
100
  displayAccounts = [
98
101
  ...accounts.filter((a) => a.is_current),
99
102
  ...accounts.filter((a) => !a.is_current),
@@ -104,19 +107,23 @@ export function createCli() {
104
107
  console.log(chalk.grey(` 提示: 当前展示前 ${limit} 个账号 (本地总计 ${totalCount} 个)。查看全部请加参数: cswitch list -l 0 或模糊搜索: cswitch list -s <关键词>\n`));
105
108
  }
106
109
  });
107
- // 3. use / switch
108
110
  program
109
111
  .command('use <identifier>')
110
112
  .alias('switch')
111
113
  .description('一键切换到指定账号 (支持输入邮箱、邮箱关键词或序号)')
112
114
  .option('--no-restart', '换号后不自动唤起 Cursor')
115
+ .option('--no-upgrade', '跳过切号前 Refresh Token 自动续期')
116
+ .option('--reset-system-id', '同时尝试重置 Windows 注册表 MachineGuid (需管理员权限)')
117
+ .option('-f, --force', '跳过过期或过时 web Token 前置拦截,强行写入本地配置')
113
118
  .action(async (identifier, options) => {
114
119
  const store = new AccountStore();
115
120
  let targetAcc = store.getByIndexOrEmail(identifier);
121
+ let pastedTokenInput = false;
116
122
  if (!targetAcc) {
117
123
  const parsed = TokenParser.parse(identifier);
118
124
  if (parsed.isValid) {
119
- console.log(chalk.cyan('\n检测到直接传入了 Token 凭据,正在同步并极速换号...'));
125
+ pastedTokenInput = true;
126
+ console.log(chalk.cyan('\n检测到直接传入了 Token 凭据,正在预检并同步账号信息...'));
120
127
  let email = parsed.email;
121
128
  if (!email) {
122
129
  try {
@@ -127,19 +134,18 @@ export function createCli() {
127
134
  if (!email) {
128
135
  email = parsed.sub ? `${parsed.sub.replace('auth0|', '')}@cursor.sh` : `account_${Date.now().toString().slice(-6)}@cursor.sh`;
129
136
  }
137
+ const existing = store.getByEmail(email);
130
138
  const usageRes = await OfficialApiClient.fetchUsage(parsed.token);
131
- const subType = usageRes.success && usageRes.subscriptionType ? usageRes.subscriptionType : 'free';
132
- const machineIds = generateMachineIds();
133
- targetAcc = {
139
+ const machineIds = existing?.machine_ids || generateMachineIds();
140
+ targetAcc = applyParsedCredentialToAccount({
141
+ parsed,
134
142
  email,
135
- token: parsed.token,
136
- workos_cursor_session_token: parsed.workosSessionToken || parsed.token,
137
- subscription_type: subType,
138
- current_period_usage: usageRes.currentPeriodUsage,
139
- machine_ids: machineIds,
140
- };
141
- store.addOrUpdate(targetAcc);
142
- 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);
143
149
  }
144
150
  else {
145
151
  console.log(chalk.red(`\n未找到匹配账号或有效 Token: "${identifier}",请使用 cswitch list 查看当前账号列表。\n`));
@@ -150,33 +156,74 @@ export function createCli() {
150
156
  const storage = new StorageBridge(paths.storageJson);
151
157
  const sqlite = new SqliteBridge(paths.sqliteDb);
152
158
  console.log(chalk.cyan(`\n正在执行换号流程,目标: ${chalk.bold.white(targetAcc.email)} ...`));
153
- if (ProcessManager.isCursorRunning()) {
154
- console.log(chalk.grey('✔ [1/4] 检测到 Cursor 运行中 -> 发送退出信号,释放 SQLite 独占锁'));
155
- 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;
156
190
  }
157
- storage.createBackup();
158
- sqlite.createBackup();
159
- console.log(chalk.grey('✔ [2/4] 创建本地安全快照备份'));
160
- const machineIds = targetAcc.machine_ids || generateMachineIds();
161
- storage.writeMachineIds(machineIds);
162
- console.log(chalk.grey(`✔ [3/4] 换载该账号专属机器指纹: ${formatMachineIdSummary(machineIds)}`));
163
- const cleanToken = TokenParser.extractTokenPart(targetAcc.token);
164
- const refreshToken = targetAcc.workos_cursor_session_token || cleanToken;
165
- storage.writeAuth(targetAcc.email, cleanToken, refreshToken);
166
- await sqlite.injectAuth(targetAcc.email, cleanToken, refreshToken);
167
- store.markCurrent(targetAcc.email);
168
- console.log(chalk.grey('✔ [4/4] 原子注入认证凭据到 SQLite 数据库'));
169
- 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`));
170
218
  if (options.restart !== false && paths.executablePath) {
171
219
  ProcessManager.launchCursor(paths.executablePath);
172
220
  console.log(chalk.green('✔ Cursor 已在后台启动\n'));
173
221
  }
174
222
  });
175
- // 4. add
176
223
  program
177
224
  .command('add [token]')
178
225
  .description('添加 Cursor 账号 (支持直接粘贴 user_xxx::eyJ... / eyJ...、纯净代登或浏览器登录)')
179
- .option('-p, --pure', '使用海外 S 级纯净住宅 IP 自动代登并提取 Token')
226
+ .option('-p, --pure', '使用云端纯净代登自动协助登录并提取 Token')
180
227
  .option('-b, --browser', '通过浏览器 OAuth 登录并自动截获授权凭据')
181
228
  .option('-e, --email <email>', '指定邮箱')
182
229
  .action(async (rawToken, options) => {
@@ -208,59 +255,54 @@ export function createCli() {
208
255
  }
209
256
  if (!rawToken) {
210
257
  console.log(chalk.yellow('\n请提供 Token 或使用选项,例:'));
211
- console.log(chalk.grey(' cswitch add --pure # 海外纯净住宅 IP 自动代登'));
212
- console.log(chalk.grey(' cswitch add --browser # 系统浏览器辅助录入'));
213
- 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;
214
263
  return;
215
264
  }
216
265
  const parsed = TokenParser.parse(rawToken);
217
266
  if (!parsed.isValid) {
218
- 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;
219
269
  return;
220
270
  }
221
271
  const fallbackEmail = parsed.sub ? `${parsed.sub.replace('auth0|', '')}@cursor.sh` : `account_${Date.now().toString().slice(-6)}@cursor.sh`;
222
272
  const email = options?.email || parsed.email || fallbackEmail;
223
- store.addOrUpdate({
273
+ printFactualTokenStatus(parsed.token, parsed.refreshToken, parsed.workosSessionToken);
274
+ const ingestRes = await upgradeAccountWebTokenOnIngest({
224
275
  email,
225
276
  token: parsed.token,
277
+ refresh_token: parsed.refreshToken,
226
278
  workos_cursor_session_token: parsed.workosSessionToken,
227
279
  });
228
- 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`));
229
283
  });
230
- // 4.1 pure (纯净云端代登直达命令)
231
284
  program
232
285
  .command('pure [account]')
233
286
  .alias('cloud-login')
234
- .description('基于海外 S 级纯净住宅 IP 自动代登 Cursor,自动收发验证码并秒提官方 Token 入库')
235
- .action(async () => {
287
+ .description('通过云端代理辅助登录 Cursor,收发邮箱验证码并获取官方 Token 入库')
288
+ .action(async (account) => {
236
289
  const paths = resolveCursorPaths();
237
290
  const storage = new StorageBridge(paths.storageJson);
238
291
  const sqlite = new SqliteBridge(paths.sqliteDb);
239
292
  const store = new AccountStore();
240
293
  const pureService = new PureLoginService();
241
- await pureService.runInteractiveFlow(store, storage, sqlite, paths.executablePath);
242
- });
243
- // 4.15 offer (老用户回归特权检测与免密直通)
244
- program
245
- .command('offer [identifier]')
246
- .alias('welcome-back')
247
- .alias('winback')
248
- .description('检测老号是否命中 Cursor 回归特权优惠 (Welcome-Back Offer),支持传 Token 或邮箱密码代登')
249
- .option('-t, --token <token>', '直接指定 SessionToken 进行检测')
250
- .action(async (identifier, options) => {
251
- const paths = resolveCursorPaths();
252
- const storage = new StorageBridge(paths.storageJson);
253
- const sqlite = new SqliteBridge(paths.sqliteDb);
254
- const store = new AccountStore();
255
- const input = options?.token || identifier;
256
- await WelcomeOfferService.runInteractiveFlow(store, storage, sqlite, paths.executablePath, input);
294
+ await pureService.runInteractiveFlow(store, storage, sqlite, paths.executablePath, {
295
+ prefilledInput: account,
296
+ });
257
297
  });
258
- // 4.2 oauth (全新无痕浏览器官方 OAuth 网页登录)
259
298
  program
260
299
  .command('oauth')
261
300
  .alias('browser-login')
262
- .description('调起全新独立无痕/隐私浏览器进行 Cursor 官方网页 OAuth 登录,并全自动纳管入库')
263
- .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) => {
264
306
  const paths = resolveCursorPaths();
265
307
  const storage = new StorageBridge(paths.storageJson);
266
308
  const sqlite = new SqliteBridge(paths.sqliteDb);
@@ -283,118 +325,122 @@ export function createCli() {
283
325
  });
284
326
  email = inputEmail || fallback;
285
327
  }
286
- const machineIds = generateMachineIds();
287
328
  console.log(chalk.grey('\n正在向 Cursor 官方同步用量与订阅计划...'));
288
329
  const usageRes = await OfficialApiClient.fetchUsage(result.accessToken);
289
330
  const existing = store.getByEmail(email);
290
- const subType = usageRes.success && usageRes.subscriptionType
291
- ? usageRes.subscriptionType
292
- : existing?.subscription_type || 'free';
293
- const newAccount = {
331
+ const machineIds = existing?.machine_ids || generateMachineIds();
332
+ const newAccount = buildOAuthAccountInfo({
294
333
  email,
295
- token: result.accessToken,
296
- workos_cursor_session_token: result.refreshToken || result.accessToken,
297
- subscription_type: subType,
298
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
299
- machine_ids: machineIds,
300
- };
334
+ accessToken: result.accessToken,
335
+ refreshToken: result.refreshToken,
336
+ authId: result.authId,
337
+ usageRes,
338
+ existing,
339
+ machineIds,
340
+ });
301
341
  store.addOrUpdate(newAccount);
302
- const copied = await copyToClipboard(newAccount.token);
303
- console.log(boxen([
304
- chalk.bold.green('🎉 官方 OAuth 登录成功!账号已自动收录入库'),
305
- chalk.dim('────────────────────────────────────────────────'),
306
- ` 登录邮箱 : ${chalk.bold.white(newAccount.email)}`,
307
- ` 会员级别 : ${formatPlanBadge(newAccount.subscription_type)}`,
308
- ` 专属指纹 : ${chalk.cyan(formatMachineIdSummary(machineIds))} ${chalk.dim('(独立隔离防封)')}`,
309
- ` 官方凭据 : ${chalk.grey(newAccount.token.slice(0, 16))}...[已加密归档]`,
310
- ` 系统剪贴板: ${copied ? chalk.green('✔ Token 已自动复制到系统剪贴板 (可直接粘贴)') : chalk.yellow('○ 请手动复制')}`,
311
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
312
- 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`));
313
351
  });
314
- // 4.2 token
315
352
  program
316
353
  .command('token [inputToken]')
317
354
  .alias('browser-token')
318
- .description('提取或录入官方 Token (若本机已登则自动秒提复制,未登调起无痕浏览器 OAuth 登录)')
319
- .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) => {
320
360
  const paths = resolveCursorPaths();
321
361
  const storage = new StorageBridge(paths.storageJson);
322
362
  const sqlite = new SqliteBridge(paths.sqliteDb);
323
363
  const store = new AccountStore();
324
- // 如果命令行直接提供了 Token 参数
364
+ const copyFormat = normalizeCopyFormatInput(options?.format) || (options?.triple ? 'triple' : undefined);
325
365
  if (inputToken && inputToken.trim()) {
326
366
  const rawToken = inputToken.trim();
327
367
  const parsed = TokenParser.parse(rawToken);
328
368
  if (!parsed.isValid) {
329
- 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;
330
371
  return;
331
372
  }
332
- const machineIds = generateMachineIds();
333
373
  console.log(chalk.grey('\n正在同步官方用量与订阅计划...'));
334
374
  const usageRes = await OfficialApiClient.fetchUsage(parsed.token);
335
375
  const fallbackEmail = parsed.sub ? `${parsed.sub.replace('auth0|', '')}@cursor.sh` : `account_${Date.now().toString().slice(-6)}@cursor.sh`;
336
376
  const email = parsed.email || fallbackEmail;
337
377
  const existing = store.getByEmail(email);
338
- const newAccount = {
378
+ const machineIds = existing?.machine_ids || generateMachineIds();
379
+ const draftAccount = applyParsedCredentialToAccount({
380
+ parsed,
339
381
  email,
340
- token: rawToken,
341
- workos_cursor_session_token: parsed.workosSessionToken || rawToken,
342
- subscription_type: usageRes.success && usageRes.subscriptionType ? usageRes.subscriptionType : (existing?.subscription_type || 'free'),
343
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
344
- machine_ids: machineIds,
345
- };
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;
346
390
  store.addOrUpdate(newAccount);
347
- const copied = await copyToClipboard(newAccount.token);
348
- console.log(boxen([
349
- chalk.bold.green('✔ 账号 Token 录入成功!已加入本地多账号库'),
350
- chalk.dim('────────────────────────────────────────────────'),
351
- ` 登录邮箱 : ${chalk.bold.white(newAccount.email)}`,
352
- ` 会员级别 : ${formatPlanBadge(newAccount.subscription_type)}`,
353
- ` 专属指纹 : ${chalk.cyan(formatMachineIdSummary(machineIds))}`,
354
- ` 官方凭据 : ${chalk.grey(rawToken.slice(0, 16))}...[已加密保护]`,
355
- ` 系统剪贴板: ${copied ? chalk.green('✔ Token 已自动复制到系统剪贴板 (可直接 Ctrl+V 粘贴)') : chalk.yellow('○ 请手动复制')}`,
356
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
357
- 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`));
358
400
  return;
359
401
  }
360
- // 1. 优先智能探测本机已登录态 (0 秒直提,免开浏览器)
361
- const localEmail = storage.readCurrentEmail() || (await sqlite.readEmail());
362
- 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
+ }
363
408
  if (localEmail && localToken) {
364
409
  console.log(chalk.cyan(`\n✔ 智能检测到本机 Cursor 已登录有效账号: ${chalk.bold.white(localEmail)}`));
365
410
  console.log(chalk.grey('正在同步官方用量与订阅计划...'));
366
411
  const existing = store.getByEmail(localEmail);
367
412
  const usageRes = await OfficialApiClient.fetchUsage(localToken);
368
- 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();
369
417
  const account = {
370
418
  email: localEmail,
371
419
  token: localToken,
420
+ refresh_token: localAuth.refreshToken || existing?.refresh_token,
421
+ workos_cursor_session_token: existing?.workos_cursor_session_token,
372
422
  subscription_type: usageRes.success && usageRes.subscriptionType ? usageRes.subscriptionType : (existing?.subscription_type || 'free'),
373
423
  current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
374
424
  machine_ids: machineIds,
375
425
  is_current: true,
376
426
  };
377
427
  store.addOrUpdate(account);
378
- const parsed = TokenParser.parse(localToken);
379
- const jwtToken = parsed.token || localToken;
380
- const copied = await copyToClipboard(jwtToken);
381
- console.log(boxen([
382
- chalk.bold.green('✔ 本机账号提取成功!已直接纳入本地库 (免开浏览器)'),
383
- chalk.dim('────────────────────────────────────────────────'),
384
- ` 登录邮箱 : ${chalk.bold.white(account.email)}`,
385
- ` 会员级别 : ${formatPlanBadge(account.subscription_type)}`,
386
- ` 专属指纹 : ${chalk.cyan(formatMachineIdSummary(machineIds))}`,
387
- ` 系统剪贴板: ${copied ? chalk.green('✔ Token 已自动复制到系统剪贴板 (可直接 Ctrl+V 粘贴)') : chalk.yellow('○ 请手动复制')}`,
388
- ].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
+ });
389
435
  return;
390
436
  }
391
- // 2. 本机未登录,调起全新无痕浏览器执行官方 OAuth 登录
392
437
  console.log(chalk.cyan('\n⚡ 本机未检测到登录态,正在调起无痕浏览器执行官方 OAuth 登录...\n'));
393
438
  const oauthRes = await OAuthReceiver.startOfficialOAuthFlow();
394
439
  if (!oauthRes.success || !oauthRes.accessToken) {
395
440
  if (oauthRes.message) {
396
441
  console.log(chalk.yellow(`\n${oauthRes.message}\n`));
397
442
  }
443
+ process.exitCode = 1;
398
444
  return;
399
445
  }
400
446
  let email = oauthRes.email;
@@ -408,86 +454,105 @@ export function createCli() {
408
454
  });
409
455
  email = inputEmail || fallback;
410
456
  }
411
- const machineIds = generateMachineIds();
412
457
  console.log(chalk.grey('\n正在向 Cursor 官方同步用量与订阅计划...'));
413
458
  const usageRes = await OfficialApiClient.fetchUsage(oauthRes.accessToken);
414
459
  const existing = store.getByEmail(email);
415
- const subType = usageRes.success && usageRes.subscriptionType
416
- ? usageRes.subscriptionType
417
- : existing?.subscription_type || 'free';
418
- const newAccount = {
460
+ const machineIds = existing?.machine_ids || generateMachineIds();
461
+ const newAccount = buildOAuthAccountInfo({
419
462
  email,
420
- token: oauthRes.accessToken,
421
- workos_cursor_session_token: oauthRes.refreshToken || oauthRes.accessToken,
422
- subscription_type: subType,
423
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
424
- machine_ids: machineIds,
425
- };
463
+ accessToken: oauthRes.accessToken,
464
+ refreshToken: oauthRes.refreshToken,
465
+ authId: oauthRes.authId,
466
+ usageRes,
467
+ existing,
468
+ machineIds,
469
+ });
426
470
  store.addOrUpdate(newAccount);
427
- const copied = await copyToClipboard(newAccount.token);
428
- console.log(boxen([
429
- chalk.bold.green('🎉 官方 OAuth 登录成功!账号已自动收录入库'),
430
- chalk.dim('────────────────────────────────────────────────'),
431
- ` 登录邮箱 : ${chalk.bold.white(newAccount.email)}`,
432
- ` 会员级别 : ${formatPlanBadge(newAccount.subscription_type)}`,
433
- ` 专属指纹 : ${chalk.cyan(formatMachineIdSummary(machineIds))} ${chalk.dim('(独立隔离防封)')}`,
434
- ` 官方凭据 : ${chalk.grey(newAccount.token.slice(0, 16))}...[已加密归档]`,
435
- ` 系统剪贴板: ${copied ? chalk.green('✔ Token 已自动复制到系统剪贴板 (可直接粘贴)') : chalk.yellow('○ 请手动复制')}`,
436
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
437
- 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`));
438
479
  });
439
- // 4.3 copy (一键拷贝指定账号或当前在用账号 Token 到剪贴板)
440
480
  program
441
- .command('copy [email]')
481
+ .command('copy [identifier]')
442
482
  .alias('cp')
443
- .description('一键复制指定账号或当前在用账号的 Token 到系统剪贴板')
444
- .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) => {
445
488
  const paths = resolveCursorPaths();
446
489
  const storage = new StorageBridge(paths.storageJson);
447
490
  const sqlite = new SqliteBridge(paths.sqliteDb);
448
491
  const store = new AccountStore();
449
- let email = targetEmail;
450
- let tokenToCopy = '';
451
- if (email) {
452
- const acc = store.getByEmail(email);
492
+ let targetAcc;
493
+ if (identifier) {
494
+ const acc = store.getByIndexOrEmail(identifier);
453
495
  if (!acc) {
454
- console.log(chalk.red(`\n未在本地库中找到邮箱为 ${email} 的账号\n`));
496
+ console.log(chalk.red(`\n未在本地库中找到匹配账号: "${identifier}"\n`));
497
+ process.exitCode = 1;
455
498
  return;
456
499
  }
457
- tokenToCopy = acc.token;
500
+ targetAcc = acc;
458
501
  }
459
502
  else {
460
- tokenToCopy = storage.readCurrentToken() || (await sqlite.readToken()) || '';
461
- email = storage.readCurrentEmail() || (await sqlite.readEmail()) || '当前账号';
462
- if (!tokenToCopy) {
463
- const currentAcc = store.getCurrentAccount();
464
- if (currentAcc) {
465
- tokenToCopy = currentAcc.token;
466
- email = currentAcc.email;
467
- }
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;
468
520
  }
469
521
  }
470
- if (!tokenToCopy) {
522
+ if (!targetAcc || !targetAcc.token) {
471
523
  console.log(chalk.yellow('\n未检测到有效 Token,请先登录或使用 cswitch token 进行提取。\n'));
524
+ process.exitCode = 1;
472
525
  return;
473
526
  }
474
- const parsed = TokenParser.parse(tokenToCopy);
475
- const jwtToken = parsed.token || tokenToCopy;
476
- const success = await copyToClipboard(jwtToken);
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;
536
+ return;
537
+ }
538
+ const copyRes = await copyPreferredAccountCredential(targetAcc, {
539
+ format: requestedFmt,
540
+ });
477
541
  console.log(boxen([
478
542
  chalk.bold.green('✔ Token 已成功复制到系统剪贴板!'),
479
543
  chalk.dim('────────────────────────────────────────────────'),
480
- ` 账号邮箱 : ${chalk.bold.white(email)}`,
481
- ` 凭据类型 : ${chalk.cyan('原生 Bearer JWT (Access Token)')}`,
482
- ` 凭据预览 : ${chalk.dim(jwtToken.slice(0, 16))}...${chalk.dim(jwtToken.slice(-12))} ${chalk.grey(`(共 ${jwtToken.length} 字符)`)}`,
483
- ` 操作提示 : ${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 可交互选择)')}`,
484
547
  ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
485
- if (!success) {
486
- console.log(chalk.yellow('提示: 自动写入剪贴板未生效,以下为 Token 明文,可手动选中复制:'));
487
- 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');
488
554
  }
489
555
  });
490
- // 5. capture
491
556
  program
492
557
  .command('capture [alias]')
493
558
  .description('一键收录当前电脑 Cursor IDE 正在登录的有效账号')
@@ -496,16 +561,23 @@ export function createCli() {
496
561
  const storage = new StorageBridge(paths.storageJson);
497
562
  const sqlite = new SqliteBridge(paths.sqliteDb);
498
563
  const store = new AccountStore();
499
- const email = storage.readCurrentEmail() || (await sqlite.readEmail());
500
- const token = storage.readCurrentToken() || (await sqlite.readToken());
564
+ const localAuth = await readLocalCursorAuth(storage, sqlite);
565
+ const email = localAuth.email;
566
+ const token = localAuth.token;
501
567
  if (!email || !token) {
502
- 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
+ }
503
574
  return;
504
575
  }
505
576
  const machineIds = storage.readMachineIds();
506
577
  store.addOrUpdate({
507
578
  email,
508
579
  token,
580
+ refresh_token: localAuth.refreshToken || undefined,
509
581
  username: alias || null,
510
582
  machine_ids: machineIds,
511
583
  is_current: true,
@@ -513,7 +585,6 @@ export function createCli() {
513
585
  console.log(chalk.green(`\n✔ 成功收录本机在用账号: ${chalk.bold.white(email)}`));
514
586
  console.log(chalk.grey(`• 绑定硬件指纹: ${formatMachineIdSummary(machineIds)}\n`));
515
587
  });
516
- // 6. dash / dashboard
517
588
  program
518
589
  .command('dash [identifier]')
519
590
  .alias('dashboard')
@@ -521,14 +592,17 @@ export function createCli() {
521
592
  .option('-t, --token <token>', '直接指定 Token 凭据免密打开控制台')
522
593
  .action(async (identifier, options) => {
523
594
  if (options?.token) {
595
+ const parsedOpt = TokenParser.parse(options.token);
596
+ const tokenForDash = parsedOpt.isValid
597
+ ? parsedOpt.workosSessionToken || parsedOpt.token
598
+ : options.token;
524
599
  console.log(chalk.cyan('\n正在使用指定 Token 调起独立浏览器并免密直达 Cursor 控制台...'));
525
- await DashboardLauncher.openDashboardWithToken(options.token, identifier || 'Direct Token User');
600
+ await DashboardLauncher.openDashboardWithToken(tokenForDash, identifier || parsedOpt.email || 'Direct Token User');
526
601
  return;
527
602
  }
528
603
  const store = new AccountStore();
529
604
  let targetAcc = identifier ? store.getByIndexOrEmail(identifier) : store.loadAll().find((a) => a.is_current);
530
605
  if (!targetAcc && identifier) {
531
- // 尝试解析是否直接传入了 Token (user_xxx:: 或 eyJ...)
532
606
  const parsed = TokenParser.parse(identifier);
533
607
  if (parsed.isValid) {
534
608
  process.stdout.write(chalk.grey('\n正在解析 Token 并同步账号信息... '));
@@ -550,14 +624,14 @@ export function createCli() {
550
624
  const subType = usageRes.success && usageRes.subscriptionType
551
625
  ? usageRes.subscriptionType
552
626
  : existing?.subscription_type || 'free';
553
- targetAcc = {
627
+ targetAcc = applyParsedCredentialToAccount({
628
+ parsed,
554
629
  email,
555
- token: parsed.token,
556
- workos_cursor_session_token: parsed.workosSessionToken || parsed.token,
557
- subscription_type: subType,
558
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
559
- machine_ids: existing?.machine_ids || generateMachineIds(),
560
- };
630
+ existing,
631
+ usageRes,
632
+ machineIds: existing?.machine_ids || generateMachineIds(),
633
+ fallbackWorkosToToken: true,
634
+ });
561
635
  if (!existing) {
562
636
  store.addOrUpdate(targetAcc);
563
637
  console.log(chalk.grey('✔ 已自动纳管录入本地多账号库'));
@@ -577,11 +651,10 @@ export function createCli() {
577
651
  console.log(chalk.cyan(`\n正在调起全新独立浏览器并免密直达 Cursor 控制台 (${targetAcc.email})...`));
578
652
  await DashboardLauncher.openDashboard(targetAcc);
579
653
  });
580
- // 6.5 mail / outlook (打开独立浏览器自动登录 Outlook 邮箱)
581
654
  program
582
655
  .command('mail [identifier]')
583
656
  .alias('outlook')
584
- .description('打开全新的独立浏览器实例并自动登录 Outlook 邮箱 (遇辅助邮箱/安全验证自动停下交接)')
657
+ .description('打开独立浏览器自动登录 Outlook 邮箱')
585
658
  .option('-p, --password <pwd>', '指定邮箱密码 (不传则优先读取已保存密码或在网页手动输入)')
586
659
  .option('-d, --dash', '同时在打开的独立浏览器新标签页中免密直达 Cursor 官网控制台')
587
660
  .option('-t, --token <token>', '指定 Cursor Token 并在浏览器新标签页中免密直达控制台')
@@ -591,7 +664,6 @@ export function createCli() {
591
664
  let emailPassword = options?.password ? String(options.password).trim() : '';
592
665
  let cursorToken = options?.token ? String(options.token).trim() : '';
593
666
  if (identifier) {
594
- // 尝试按多段式解析 (支持 email----password 等格式)
595
667
  const pureLogin = new PureLoginService();
596
668
  const parsed = pureLogin.parseAccountString(identifier);
597
669
  if (parsed.email) {
@@ -601,7 +673,6 @@ export function createCli() {
601
673
  }
602
674
  }
603
675
  else {
604
- // 尝试从已有账号库匹配
605
676
  const targetAcc = store.getByIndexOrEmail(identifier);
606
677
  if (targetAcc) {
607
678
  email = targetAcc.email;
@@ -618,7 +689,6 @@ export function createCli() {
618
689
  }
619
690
  }
620
691
  else {
621
- // 未传 identifier,优先使用当前在用账号,或列表中第一个账号
622
692
  const currentAcc = store.loadAll().find((a) => a.is_current) || store.loadAll()[0];
623
693
  if (currentAcc) {
624
694
  email = currentAcc.email;
@@ -632,9 +702,9 @@ export function createCli() {
632
702
  }
633
703
  if (!email) {
634
704
  console.log(chalk.yellow('\n未检测到可用邮箱,请使用 "cswitch mail <email>" 或直接进入 cswitch 主菜单。\n'));
705
+ process.exitCode = 1;
635
706
  return;
636
707
  }
637
- // 若指定了 -d 但未指定 token,尝试从库中寻找匹配账号的 token
638
708
  if (options?.dash && !cursorToken) {
639
709
  const matched = store.getByEmail(email) || store.loadAll().find((a) => a.email.toLowerCase() === email.toLowerCase());
640
710
  if (matched?.token) {
@@ -644,7 +714,7 @@ export function createCli() {
644
714
  const shouldOpenDash = Boolean(options?.dash || (options?.token && cursorToken));
645
715
  console.log(chalk.cyan(`\n正在调起全新独立浏览器并自动登录 ${email}...`));
646
716
  if (shouldOpenDash && cursorToken) {
647
- console.log(chalk.green(` [联动] 同时在浏览器新标签页免密打开 Cursor 控制台 (Token: ${cursorToken.slice(0, 15)}...)`));
717
+ console.log(chalk.green(` [联动] 同时在浏览器新标签页免密打开 Cursor 控制台 (Token: ${maskToken(cursorToken)})`));
648
718
  }
649
719
  const res = await OutlookLauncher.openMailbox({
650
720
  email,
@@ -654,24 +724,22 @@ export function createCli() {
654
724
  });
655
725
  OutlookLauncher.printResultCard(res);
656
726
  });
657
- // 7. refund / aozai / seat (奥仔退款)
658
727
  program
659
728
  .command('refund [identifier]')
660
- .alias('aozai')
661
729
  .alias('seat')
662
- .description('奥仔退款:执行席位退款,账号退出并恢复为 Free 免费状态')
663
- .option('-c, --card <code>', '使用指定席位卡密 (不传则使用已保存卡密或提示输入)')
730
+ .description('Cursor 退款服务:使用卡密自助完成退款处理,账号退出席位并恢复为 Free 免费状态')
731
+ .option('-c, --card <code>', '使用指定退款卡密 (不传则使用已保存卡密或提示输入)')
664
732
  .option('-t, --token <token>', '直接指定 Cursor Session Token 执行退款')
665
733
  .option('-s, --status', '查询当前卡密剩余点数与扣点费率')
666
734
  .option('-u, --usage', '查看卡密历史使用与退款流水明细')
667
- .option('--set-card <code>', '保存默认席位卡密到本地配置')
668
- .option('--api-base <url>', '自定义奥仔退款服务 API 网关地址')
735
+ .option('--set-card <code>', '保存默认退款卡密到本地配置')
736
+ .option('--api-base <url>', '自定义 Cursor 退款服务 API 网关地址')
669
737
  .option('-y, --yes', '自动化免确认模式 (自动同意扣费与重启 Cursor)')
670
738
  .action(async (identifier, options) => {
671
739
  const refundService = new RefundService(options?.apiBase);
672
740
  if (options?.setCard) {
673
741
  refundService.getConfigStore().setSeatCardCode(options.setCard);
674
- console.log(chalk.green(`\n✔ 默认席位卡密已保存: ${options.setCard}\n`));
742
+ console.log(chalk.green(`\n✔ 默认退款卡密已保存: ${maskToken(options.setCard)}\n`));
675
743
  return;
676
744
  }
677
745
  if (options?.status) {
@@ -680,8 +748,8 @@ export function createCli() {
680
748
  return;
681
749
  const balRes = await refundService.getClient().getBalance(cardRes.auth.token);
682
750
  const b = balRes.data || cardRes.auth;
683
- console.log(chalk.bold.cyan('\n● 奥仔席位退款卡密状态:'));
684
- console.log(`• 卡密编号 : ${chalk.white(cardRes.cardCode)}`);
751
+ console.log(chalk.bold.cyan('\n● Cursor 退款服务卡密状态:'));
752
+ console.log(`• 卡密编号 : ${chalk.white(maskToken(cardRes.cardCode))}`);
685
753
  console.log(`• 剩余点数 : ${chalk.bold.green(b.remaining)} 点`);
686
754
  console.log(`• 已用点数 : ${chalk.yellow(b.used)} 点`);
687
755
  console.log(`• 单次扣点 : ${chalk.magenta(b.pointsPerOp)} 点`);
@@ -711,7 +779,85 @@ export function createCli() {
711
779
  autoYes: Boolean(options?.yes),
712
780
  });
713
781
  });
714
- // 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
+ });
715
861
  const idCmd = program.command('id').description('Cursor 机器硬件指纹 (Machine ID) 管理');
716
862
  idCmd
717
863
  .command('status')
@@ -728,16 +874,36 @@ export function createCli() {
728
874
  });
729
875
  idCmd
730
876
  .command('reset')
731
- .description('一键备份并重置全套崭新的随机机器码')
732
- .action(() => {
877
+ .description('一键备份并重置全套崭新的随机机器码 (同步写入 storage.json、state.vscdb 与 machineid)')
878
+ .option('--system', '同时尝试重置 Windows 注册表 MachineGuid (需管理员权限)')
879
+ .action(async (options) => {
733
880
  const paths = resolveCursorPaths();
734
881
  const storage = new StorageBridge(paths.storageJson);
882
+ const sqlite = new SqliteBridge(paths.sqliteDb);
735
883
  const newIds = generateMachineIds();
736
884
  storage.createBackup();
737
- storage.writeMachineIds(newIds);
738
- 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('');
739
906
  });
740
- // 8. remove / rm
741
907
  program
742
908
  .command('remove [identifier]')
743
909
  .alias('rm')
@@ -754,28 +920,37 @@ export function createCli() {
754
920
  const acc = store.getByIndexOrEmail(identifier);
755
921
  if (!acc) {
756
922
  console.log(chalk.red(`\n未找到匹配账号: "${identifier}"\n`));
923
+ process.exitCode = 1;
757
924
  return;
758
925
  }
759
926
  store.remove(acc.email);
760
927
  console.log(chalk.green(`\n✔ 账号 ${acc.email} 已成功移除。\n`));
761
928
  });
762
- // 9. import / export
763
929
  program
764
930
  .command('import <filePath>')
765
- .description('从文本或 JSON 文件批量导入账号')
931
+ .description('从文本 (支持 ---- 多段账号行与裸 Token) 或 JSON 文件批量导入账号')
766
932
  .action((filePath) => {
767
933
  if (!fs.existsSync(filePath)) {
768
934
  console.log(chalk.red(`\n文件不存在: ${filePath}\n`));
935
+ process.exitCode = 1;
769
936
  return;
770
937
  }
771
938
  const store = new AccountStore();
772
939
  const content = fs.readFileSync(filePath, 'utf8');
773
940
  let count = 0;
774
- if (filePath.endsWith('.json')) {
775
- 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
+ }
776
951
  if (Array.isArray(arr)) {
777
952
  for (const item of arr) {
778
- if (item.email && item.token) {
953
+ if (item && item.email && (item.token || item.email_password)) {
779
954
  store.addOrUpdate(item);
780
955
  count++;
781
956
  }
@@ -783,18 +958,7 @@ export function createCli() {
783
958
  }
784
959
  }
785
960
  else {
786
- const lines = content.split('\n');
787
- for (const line of lines) {
788
- const parsed = TokenParser.parse(line);
789
- if (parsed.isValid && parsed.email) {
790
- store.addOrUpdate({
791
- email: parsed.email,
792
- token: parsed.token,
793
- workos_cursor_session_token: parsed.workosSessionToken,
794
- });
795
- count++;
796
- }
797
- }
961
+ count = importAccountsFromText(content, store);
798
962
  }
799
963
  console.log(chalk.green(`\n✔ 导入完成!共新增/更新 ${count} 个账号。\n`));
800
964
  });
@@ -805,10 +969,9 @@ export function createCli() {
805
969
  const store = new AccountStore();
806
970
  const accounts = store.loadAll();
807
971
  const outPath = targetPath || `cursor_accounts_backup_${Date.now()}.json`;
808
- fs.writeFileSync(outPath, JSON.stringify(accounts, null, 2), 'utf8');
972
+ writeSecureFileSync(outPath, JSON.stringify(accounts, null, 2));
809
973
  console.log(chalk.green.bold(`\n✔ 成功导出 ${accounts.length} 个账号至: ${outPath}\n`));
810
974
  });
811
- // 10. update / upgrade
812
975
  program
813
976
  .command('update')
814
977
  .alias('upgrade')