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/menu.js CHANGED
@@ -1,10 +1,6 @@
1
- /**
2
- * 适合中国人习惯的 TUI 终端交互式主菜单
3
- * 基于 @inquirer/prompts + chalk + boxen 打造
4
- */
5
1
  import chalk from 'chalk';
6
2
  import boxen from 'boxen';
7
- import { liveMenu, quickSelect, Separator } from './utils/live-menu.js';
3
+ import { liveMenu, quickSelect, Separator, leaveAltScreenIfActive, measureAnsiWidth, computeHudInnerWidth, } from './utils/live-menu.js';
8
4
  import { AccountStore } from './core/account-store.js';
9
5
  import { resolveCursorPaths, findCursorExecutable } from './core/cursor-paths.js';
10
6
  import { ConfigStore } from './core/config-store.js';
@@ -16,17 +12,22 @@ import { OutlookLauncher } from './core/outlook-launcher.js';
16
12
  import { OAuthReceiver } from './core/oauth-receiver.js';
17
13
  import { TokenParser } from './core/token-parser.js';
18
14
  import { generateMachineIds, formatMachineIdSummary } from './core/fingerprint.js';
19
- import { openBrowserUrl } from './utils/browser-utils.js';
15
+ import { applyMachineIdsToCursor, executeAccountSwitch, readLocalCursorAuth, } from './core/switch-orchestrator.js';
16
+ import { applyParsedCredentialToAccount, buildOAuthAccountInfo, upgradeAccountWebTokenOnIngest, } from './core/token-exchange.js';
20
17
  import { renderAccountTable } from './utils/table-renderer.js';
21
18
  import { getExpiryStatus } from './utils/time-formatter.js';
22
19
  import { maskToken } from './utils/security.js';
23
20
  import { formatPlanName, formatPlanBadge } from './utils/plan-formatter.js';
21
+ import { printFactualTokenStatus, printIngestUpgradeResult, resolveStaleSwitchWithHealing, } from './utils/token-preflight-ui.js';
22
+ import { copyPreferredAccountCredential, printExtractedCredentialsResult, runInteractiveCopyAccountMenu, } from './utils/credential-bundle-ui.js';
24
23
  import { RefundService } from './core/refund-service.js';
24
+ import { ExtractService } from './core/extract-service.js';
25
+ import { handleExtractCheckoutMenu } from './core/extract-menu.js';
25
26
  import { PureLoginService } from './core/pure-login-service.js';
26
27
  import { OfficialApiClient } from './core/official-api.js';
27
28
  import { safeInput, safeConfirm, safeCheckbox, safePressAnyKey } from './utils/prompt-utils.js';
28
- import { UpdateChecker, CURRENT_VERSION } from './core/update-checker.js';
29
- import { copyToClipboard } from './utils/clipboard.js';
29
+ import { UpdateChecker, CURRENT_VERSION, IS_PRIVATE_EDITION } from './core/update-checker.js';
30
+ import { importAccountsFromText } from './utils/account-text-importer.js';
30
31
  import fs from 'node:fs';
31
32
  export async function runInteractiveMenu() {
32
33
  const store = new AccountStore();
@@ -34,19 +35,118 @@ export async function runInteractiveMenu() {
34
35
  const storage = new StorageBridge(paths.storageJson);
35
36
  const sqlite = new SqliteBridge(paths.sqliteDb);
36
37
  const updateChecker = new UpdateChecker();
37
- // 循环运行主菜单,直到用户选择退出
38
38
  while (true) {
39
- console.clear();
40
39
  const accounts = store.loadAll();
41
- const currentEmail = storage.readCurrentEmail() || (await sqlite.readEmail()) || '未登录';
40
+ const localAuth = await readLocalCursorAuth(storage, sqlite);
41
+ const currentEmail = localAuth.email || '未登录';
42
42
  const currentAcc = accounts.find((a) => a.email.toLowerCase() === currentEmail.toLowerCase());
43
- // 0ms 读取本地版本更新缓存 (若超期则自动在后台静默发起异步检查)
44
43
  const updateInfo = await updateChecker.check(false);
45
44
  const planType = formatPlanName(currentAcc?.subscription_type);
46
45
  const cycleEnd = currentAcc?.current_period_usage?.billingCycleEnd;
47
46
  const planBadge = `[${formatPlanBadge(currentAcc?.subscription_type)}]`;
48
47
  const devId = currentAcc?.machine_ids ? formatMachineIdSummary(currentAcc.machine_ids) : '--';
49
- // 动态渲染实时走字 HUD 面板 (每秒平滑走字)
48
+ const menuChoices = [
49
+ {
50
+ name: '1. 切换账号',
51
+ value: 'switch',
52
+ hint: '一键切换登录账号,自动绑定专属防封设备码',
53
+ shortHint: '一键切换登录账号与防封设备码',
54
+ description: '切换 Cursor 登录账号,自动绑定该账号的专属防关联设备码',
55
+ },
56
+ {
57
+ name: '2. 添加与管理账号',
58
+ value: 'add',
59
+ hint: '添加新账号、粘贴 Token、批量导入或删除',
60
+ shortHint: '添加、批量导入或管理本地账号',
61
+ description: '支持网页登录、粘贴 Token、批量导入或删除本地保存的账号',
62
+ },
63
+ {
64
+ name: '3. 账号看板与搜索',
65
+ value: 'radar',
66
+ hint: '查看各账号会员级别、剩余用量与到期时间',
67
+ shortHint: '查看各账号会员级别与剩余用量',
68
+ description: '一屏浏览所有本地账号的会员类型、高级请求余量与到期时间',
69
+ },
70
+ new Separator(),
71
+ {
72
+ name: '4. 用 Token 打开 Cursor 官网控制台',
73
+ value: 'dashboard',
74
+ hint: '免密打开当前账号的 Cursor 官网管理后台',
75
+ shortHint: '免密打开当前账号官网后台',
76
+ description: '调起独立浏览器免密登录,直接查看当前账号的官网设置与订阅用量',
77
+ },
78
+ {
79
+ name: '5. 打开 Outlook 邮箱 (自动登录 · m)',
80
+ value: 'outlook_mail',
81
+ key: 'm',
82
+ hint: '调起独立浏览器并自动填密登录 Outlook (按 m)',
83
+ shortHint: '自动填密登录 Outlook 网页邮箱',
84
+ description: '调起独立浏览器窗口,自动填入邮箱密码登录 Outlook 查收邮件 (按 m 直达)',
85
+ },
86
+ {
87
+ name: '6. 提取本机或网页 Token',
88
+ value: 'extract',
89
+ hint: '一键读取当前已登 Token,或登录提取新凭据',
90
+ shortHint: '读取本机或浏览器登录提取 Token',
91
+ description: '读取本机 Cursor 当前登录的 Token 凭据,或打开浏览器重新登录提取',
92
+ },
93
+ new Separator(),
94
+ {
95
+ name: '7. Cursor 退款服务',
96
+ value: 'refund',
97
+ hint: '使用退款卡密办理退款,自动退回 Free 免费版',
98
+ shortHint: '使用卡密办理退款并退回免费版',
99
+ description: '输入退款卡密办理自助退款,账号自动解除订阅并退回 Free 免费版',
100
+ },
101
+ {
102
+ name: '8. 提取老套餐付款链接',
103
+ value: 'extract_checkout',
104
+ hint: '使用提链卡密生成官方老套餐支付宝付款链接',
105
+ shortHint: '使用提链卡密生成老套餐付款链接',
106
+ description: '使用提链卡密生成官方老套餐(支持支付宝)付款直链(成功才扣次)',
107
+ },
108
+ {
109
+ name: '9. Cursor 纯净代登',
110
+ value: 'pure_login',
111
+ hint: '通过纯净海外网络辅助登录,安全换取 60 天 Token',
112
+ shortHint: '通过纯净代理辅助登录换取 Token',
113
+ description: '在纯净海外网络环境下辅助完成登录与验证码校验,换取 60 天长效 Token',
114
+ },
115
+ new Separator(),
116
+ {
117
+ name: '10. 硬件指纹管理',
118
+ value: 'fingerprint',
119
+ hint: '查看当前设备标识码,或一键重置全新防封硬件码',
120
+ shortHint: '查看或重置本机防封设备硬件码',
121
+ description: '查看当前设备标识码(Machine ID),或一键重置为全新的独立防封硬件指纹',
122
+ },
123
+ {
124
+ name: '11. 快照安全备份',
125
+ value: 'backup',
126
+ hint: '一键备份或恢复本地账号数据与客户端配置文件',
127
+ shortHint: '一键备份或恢复本地账号与配置',
128
+ description: '为本地账号列表与 Cursor 核心配置文件创建安全备份,支持随时一键还原',
129
+ },
130
+ new Separator(),
131
+ {
132
+ name: updateInfo.hasUpdate
133
+ ? `u. 检查更新 / 立即升级 ${chalk.green.bold(`(新版 v${updateInfo.latestVersion})`)}`
134
+ : 'u. 检查更新 / 立即升级',
135
+ value: 'upgrade',
136
+ key: 'u',
137
+ hint: '在线检查最新版本,并支持一键自动更新 (按 u)',
138
+ shortHint: '检查是否有新版本并一键自动更新',
139
+ description: '在线检测最新版本,支持一键平滑自动更新升级 (按 u 直达)',
140
+ },
141
+ new Separator(),
142
+ {
143
+ name: '0. 退出程序',
144
+ value: 'exit',
145
+ hint: '关闭交互式菜单,安全返回系统命令行终端',
146
+ shortHint: '关闭菜单,返回命令行终端',
147
+ description: '退出 Cursor-Switch 交互菜单,安全返回系统终端',
148
+ },
149
+ ];
50
150
  const getHeader = () => {
51
151
  const expiry = getExpiryStatus(cycleEnd);
52
152
  const isRunning = ProcessManager.isCursorRunning();
@@ -55,19 +155,31 @@ export async function runInteractiveMenu() {
55
155
  ? chalk.bgRed.white.bold(` ${expiry.countdownText} `)
56
156
  : chalk.cyan(expiry.countdownText);
57
157
  const updateNotice = updateInfo.hasUpdate
58
- ? `\n ${chalk.bgYellow.black.bold(' 发现新版 ')} ${chalk.bold.yellow(`v${updateInfo.latestVersion}`)} ${chalk.dim('按 [u] 快捷一键自动升级')}`
158
+ ? `\n ${chalk.bgYellow.black.bold(' 发现新版 ')} ${chalk.bold.yellow(`v${updateInfo.latestVersion}`)} ${chalk.dim('按 [u] 一键升级')}`
59
159
  : '';
160
+ const accLine = ` 当前账号 : ${chalk.bold.white(currentEmail)} ${planBadge}`;
161
+ const expLine = ` 到期时间 : ${chalk.white(expiry.formattedDate)} ${expiryPill}`;
162
+ const fpLine = ` 设备指纹 : ${chalk.cyan(devId)} ${chalk.dim('(独立隔离)')} ${chalk.dim('Cursor:')} ${cursorTag}`;
163
+ const cols = process.stdout.columns || 84;
164
+ const modeBadge = IS_PRIVATE_EDITION
165
+ ? `${chalk.green('●')} ${chalk.green('本地私有增强版')}`
166
+ : `${chalk.green('●')} ${chalk.green('纯本地运行 · 离线安全')}`;
167
+ const leftTitle = `${chalk.bold.cyan('CURSOR-SWITCH')} ${chalk.dim('v' + CURRENT_VERSION)}`;
168
+ const minHeaderWidth = measureAnsiWidth(leftTitle) + 2 + measureAnsiWidth(modeBadge);
169
+ const minHudContentWidth = Math.max(minHeaderWidth, measureAnsiWidth(accLine), measureAnsiWidth(expLine), measureAnsiWidth(fpLine));
170
+ const innerWidth = computeHudInnerWidth(menuChoices, cols, minHudContentWidth);
171
+ const titleGap = Math.max(2, innerWidth - measureAnsiWidth(leftTitle) - measureAnsiWidth(modeBadge));
60
172
  const bannerText = [
61
- `${chalk.bold.cyan('CURSOR-SWITCH')} ${chalk.dim('v' + CURRENT_VERSION)} ${chalk.dim('●')} ${chalk.green('纯本地运行 · 离线安全')}`,
62
- chalk.dim('──────────────────────────────────────────────────────────────────'),
63
- ` 当前账号 : ${chalk.bold.white(currentEmail)} ${planBadge}`,
64
- ` 具体到期 : ${chalk.grey(expiry.formattedDate)} ${expiryPill}`,
65
- ` 设备指纹 : ${chalk.magenta(devId)} ${chalk.dim('(独立隔离)')} ${chalk.dim('Cursor:')} ${cursorTag}`,
173
+ `${leftTitle}${' '.repeat(titleGap)}${modeBadge}`,
174
+ chalk.dim('─'.repeat(innerWidth)),
175
+ accLine,
176
+ expLine,
177
+ fpLine,
66
178
  ].join('\n') + updateNotice;
67
179
  return boxen(bannerText, {
68
180
  padding: { top: 0, bottom: 0, left: 1, right: 1 },
69
181
  margin: { top: 0, bottom: 0, left: 0, right: 0 },
70
- borderColor: updateInfo.hasUpdate ? 'yellow' : 'gray',
182
+ borderColor: updateInfo.hasUpdate ? 'yellow' : 'cyan',
71
183
  borderStyle: 'round',
72
184
  });
73
185
  };
@@ -76,67 +188,30 @@ export async function runInteractiveMenu() {
76
188
  action = await liveMenu({
77
189
  getHeader,
78
190
  message: '操作菜单:',
79
- choices: [
80
- { name: '1. 切换账号', value: 'switch', description: '快速切换账号并激活专属防封硬件指纹' },
81
- { name: '2. 添加与管理账号', value: 'add', description: '录入新账号 (Token/代登/截获) 或清理删除已有旧账号' },
82
- { name: '3. 账号看板与搜索', value: 'radar', description: '查看额度余量、到期倒计时、模糊检索与账号删除清理' },
83
- new Separator(),
84
- { name: '4. 打开 Cursor 官网控制台 (用 Token 免密直达)', value: 'dashboard', description: '注入当前账号 Token 免密调起独立浏览器,直达 Cursor 官网控制台与设置页' },
85
- {
86
- name: '5. 打开 Outlook 邮箱 (独立浏览器自动登录)',
87
- value: 'outlook_mail',
88
- key: 'm',
89
- description: '全新独立隔离浏览器实例,自动登录 Outlook 邮箱,遇辅助邮箱/安全验证自动停下交接 (按 m 快捷直达)',
90
- },
91
- { name: '6. 提取 Token (本地浏览器)', value: 'extract', description: '智能读取本机 Cursor 已登 Token,或调起本地无痕浏览器抓取 Token 凭据' },
92
- new Separator(),
93
- { name: '7. 纯净代登', value: 'pure_login', description: '远程调用海外纯净住宅 IP 云端代登,自动过盾收码并秒提 Token' },
94
- { name: '8. 奥仔退款', value: 'refund', description: '席位退款处理,账号退出并恢复为 Free 免费状态' },
95
- new Separator(),
96
- { name: '9. 硬件指纹管理', value: 'fingerprint', description: '查看或重置专属防封虚拟硬件码' },
97
- { name: '10. 快照安全备份', value: 'backup', description: '安全备份本地配置与 SQLite 数据库' },
98
- {
99
- name: 'g. 打开 AI 折腾局官网 (getdoubao.com)',
100
- value: 'website',
101
- key: 'g',
102
- description: '调起浏览器直达 AI 折腾局官网,查看折腾手册、开源工具与卡网服务 (按 g 快捷直达)',
103
- },
104
- {
105
- name: 'q. 官方 QQ 交流群 (群号: 1007446249)',
106
- value: 'qq_group',
107
- key: 'q',
108
- description: '加入官方交流群,自动将群号复制到剪贴板,支持答疑、交流与售后 (按 q 快捷直达)',
109
- },
110
- {
111
- name: updateInfo.hasUpdate
112
- ? `u. 检查更新 / 立即升级 ${chalk.green.bold(`(有新版 v${updateInfo.latestVersion})`)}`
113
- : 'u. 检查更新 / 立即升级',
114
- value: 'upgrade',
115
- key: 'u',
116
- description: '在线检查新版本,支持从官方及国内镜像全自动一键自更新 (按 u 快捷直达)',
117
- },
118
- new Separator(),
119
- { name: '0. 退出程序', value: 'exit', description: '结束运行并返回终端' },
120
- ],
121
- pageSize: 22,
191
+ choices: menuChoices,
192
+ pageSize: 26,
122
193
  tickIntervalMs: 1000,
194
+ altScreen: true,
123
195
  });
124
196
  }
125
197
  catch (err) {
126
198
  if (err?.name === 'ExitPromptError') {
199
+ leaveAltScreenIfActive();
127
200
  process.stdout.write('\x1b[?25h\n');
128
- console.log(chalk.grey('\n感谢使用 Cursor-Switch,祝您编码愉快!'));
129
- console.log(chalk.dim('官方交流群: 1007446249 | 官网: https://getdoubao.com\n'));
201
+ console.log(chalk.grey('\n已退出 Cursor-Switch。\n'));
130
202
  process.exit(0);
131
203
  }
132
204
  throw err;
133
205
  }
134
206
  if (action === 'exit') {
207
+ leaveAltScreenIfActive();
135
208
  process.stdout.write('\x1b[?25h\n');
136
- console.log(chalk.grey('\n感谢使用 Cursor-Switch,祝您编码愉快!'));
137
- console.log(chalk.dim('官方交流群: 1007446249 | 官网: https://getdoubao.com\n'));
209
+ console.log(chalk.grey('\n已退出 Cursor-Switch。\n'));
138
210
  process.exit(0);
139
211
  }
212
+ if (process.stdout.isTTY) {
213
+ console.clear();
214
+ }
140
215
  try {
141
216
  if (action === 'switch') {
142
217
  await handleSwitchMenu(store, storage, sqlite, paths.executablePath);
@@ -156,6 +231,9 @@ export async function runInteractiveMenu() {
156
231
  else if (action === 'refund') {
157
232
  await handleRefundMenu(store, currentAcc);
158
233
  }
234
+ else if (action === 'extract_checkout') {
235
+ await handleExtractCheckoutMenu(store, currentAcc);
236
+ }
159
237
  else if (action === 'pure_login') {
160
238
  const pureService = new PureLoginService();
161
239
  await pureService.runInteractiveFlow(store, storage, sqlite, paths.executablePath);
@@ -164,23 +242,18 @@ export async function runInteractiveMenu() {
164
242
  await handleSmartExtractAction(store, storage, sqlite, paths.executablePath);
165
243
  }
166
244
  else if (action === 'fingerprint') {
167
- await handleFingerprintMenu(storage, currentAcc);
245
+ await handleFingerprintMenu(storage, currentAcc, sqlite);
168
246
  }
169
247
  else if (action === 'backup') {
170
248
  await handleBackupAction(storage, sqlite);
171
249
  }
172
- else if (action === 'website') {
173
- await handleOpenWebsiteAction();
174
- }
175
- else if (action === 'qq_group') {
176
- await handleQqGroupAction();
177
- }
178
250
  else if (action === 'upgrade') {
179
251
  await handleUpgradeMenu(updateChecker);
180
252
  }
181
253
  }
182
254
  catch (err) {
183
255
  if (err?.name === 'ExitPromptError') {
256
+ leaveAltScreenIfActive();
184
257
  process.stdout.write('\x1b[?25h\n');
185
258
  process.exit(0);
186
259
  }
@@ -188,9 +261,6 @@ export async function runInteractiveMenu() {
188
261
  }
189
262
  }
190
263
  }
191
- /**
192
- * 换号交互子流程
193
- */
194
264
  async function handleSwitchMenu(store, storage, sqlite, execPath) {
195
265
  const accounts = store.loadAll();
196
266
  if (accounts.length === 0) {
@@ -204,33 +274,32 @@ async function handleSwitchMenu(store, storage, sqlite, execPath) {
204
274
  }
205
275
  return;
206
276
  }
207
- // 优先把当前在用的账号排在前面
208
277
  const sortedAccounts = [
209
278
  ...accounts.filter((a) => a.is_current),
210
279
  ...accounts.filter((a) => !a.is_current),
211
280
  ];
212
281
  const choices = [
213
- { name: '0. 返回主菜单', value: '__back__' },
282
+ { name: '0. 返回', value: '__back__' },
214
283
  {
215
- name: 't. 录入 Token 极速换号...',
284
+ name: 't. 录入 Token 切换',
216
285
  value: '__token_switch__',
217
286
  key: 't',
218
- description: '直接粘贴 user_xxx:: 或 eyJ... 凭据,自动建档入库并立即换号切换',
287
+ description: '粘贴凭据自动入库并切换',
219
288
  },
220
289
  ];
221
290
  if (accounts.length > 10) {
222
291
  choices.push({
223
- name: 's. 搜索账号...',
292
+ name: 's. 搜索账号',
224
293
  value: '__search__',
225
294
  key: 's',
226
- description: '输入关键词模糊筛选账号 (支持邮箱、域名或会员级别)',
295
+ description: '按邮箱或套餐筛选',
227
296
  });
228
297
  }
229
298
  choices.push({
230
- name: 'd. 移除/清理旧账号...',
299
+ name: 'd. 清理账号',
231
300
  value: '__cleanup__',
232
301
  key: 'd',
233
- description: '从本地库中删除不需要的账号或批量清理失效账号',
302
+ description: '删除指定或失效账号',
234
303
  });
235
304
  choices.push(new Separator());
236
305
  sortedAccounts.forEach((acc, index) => {
@@ -248,7 +317,8 @@ async function handleSwitchMenu(store, storage, sqlite, execPath) {
248
317
  });
249
318
  });
250
319
  const selectedEmail = await quickSelect({
251
- message: '选择目标账号 (直接按序号秒切,按 t 录入Token,按 0 返回):',
320
+ header: chalk.bold.cyan('● 切换账号'),
321
+ message: '选择账号 (序号 / t / 0):',
252
322
  choices,
253
323
  pageSize: 12,
254
324
  });
@@ -297,13 +367,10 @@ async function handleSwitchMenu(store, storage, sqlite, execPath) {
297
367
  return;
298
368
  await executeSwitchAccount(store, storage, sqlite, targetAcc, execPath);
299
369
  }
300
- /**
301
- * 直接录入 Token 极速切换子流程 (Token Fast Switch)
302
- */
303
370
  async function handleTokenDirectSwitch(store, storage, sqlite, execPath) {
304
371
  console.clear();
305
372
  console.log(chalk.bold.cyan('\n● 录入 Token 极速换号 (Token Fast Switch)\n'));
306
- console.log(chalk.grey('支持直接粘贴 user_xxx::eyJ... 会话凭据或 eyJ... 访问凭据 (输入 0 或 q 取消返回)\n'));
373
+ console.log(chalk.grey('支持直接粘贴 一段 (user_xxx::eyJ... / eyJ...) 或 三段完整凭据 (Access----Refresh----Web) (输入 0 或 q 取消)\n'));
307
374
  const rawInput = await safeInput({
308
375
  message: '请在此粘贴 Token 凭据',
309
376
  });
@@ -313,12 +380,11 @@ async function handleTokenDirectSwitch(store, storage, sqlite, execPath) {
313
380
  const rawToken = rawInput.trim();
314
381
  const parsed = TokenParser.parse(rawToken);
315
382
  if (!parsed.isValid) {
316
- console.log(chalk.red('\n未识别到有效的 Token 格式,仅支持 user_xxx:: 或 eyJ... 格式。\n'));
383
+ console.log(chalk.red('\n未识别到有效的 Token 格式,支持一段 (user_xxx::eyJ... / eyJ...) 或三段打包串。\n'));
317
384
  await pressAnyKey();
318
385
  return;
319
386
  }
320
387
  process.stdout.write(chalk.grey('\n正在连接 Cursor 官方端点同步账号信息... '));
321
- // 1. 优先尝试从官方 RPC 接口精准获取真实绑定邮箱
322
388
  let email;
323
389
  try {
324
390
  const fetchedEmail = await OfficialApiClient.fetchEmail(parsed.token);
@@ -338,58 +404,78 @@ async function handleTokenDirectSwitch(store, storage, sqlite, execPath) {
338
404
  });
339
405
  email = inputEmail || fallback;
340
406
  }
341
- // 2. 查询用量与会员订阅
342
407
  const usageRes = await OfficialApiClient.fetchUsage(parsed.token);
343
408
  const existing = store.getByEmail(email);
344
- const subType = usageRes.success && usageRes.subscriptionType
345
- ? usageRes.subscriptionType
346
- : existing?.subscription_type || 'free';
347
- console.log(chalk.green(`✔ ${email} [${formatPlanName(subType)}]`));
348
- // 3. 生成专属防封硬件指纹并建档入库
349
409
  const machineIds = existing?.machine_ids || generateMachineIds();
350
- const targetAcc = {
410
+ const targetAcc = applyParsedCredentialToAccount({
411
+ parsed,
351
412
  email,
352
- token: parsed.token,
353
- workos_cursor_session_token: parsed.workosSessionToken || parsed.token,
354
- subscription_type: subType,
355
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
356
- machine_ids: machineIds,
357
- };
358
- store.addOrUpdate(targetAcc);
359
- await copyToClipboard(targetAcc.token);
360
- console.log(chalk.green(`✔ 账号已成功纳管入库,正在立即执行换号切换...\n`));
361
- // 4. 立即执行一键换号
362
- await executeSwitchAccount(store, storage, sqlite, targetAcc, execPath);
413
+ existing,
414
+ usageRes,
415
+ machineIds,
416
+ fallbackWorkosToToken: true,
417
+ });
418
+ printFactualTokenStatus(targetAcc.token, targetAcc.refresh_token, targetAcc.workos_cursor_session_token);
419
+ console.log(chalk.green(`✔ ${email} [${formatPlanName(targetAcc.subscription_type)}]`));
420
+ console.log(chalk.cyan('\n正在执行前置校验与换号准备...'));
421
+ const switchedAcc = await executeSwitchAccount(store, storage, sqlite, targetAcc, execPath);
422
+ if (switchedAcc) {
423
+ if (switchedAcc.email === targetAcc.email && switchedAcc.token === targetAcc.token) {
424
+ store.addOrUpdate({ ...switchedAcc, is_current: true });
425
+ }
426
+ await copyPreferredAccountCredential(switchedAcc);
427
+ }
363
428
  }
364
- /**
365
- * 执行一键换号的核心原子流程
366
- */
367
429
  async function executeSwitchAccount(store, storage, sqlite, targetAcc, execPath) {
368
430
  console.log(chalk.cyan(`\n正在执行换号流程,目标: ${chalk.bold.white(targetAcc.email)} ...`));
369
- // 1. 关闭 Cursor
370
- if (ProcessManager.isCursorRunning()) {
371
- console.log(chalk.grey('✔ [1/4] 检测到 Cursor 运行中 -> 发送退出信号,释放 SQLite 独占锁'));
372
- await ProcessManager.closeCursor();
431
+ const paths = resolveCursorPaths();
432
+ const switchRes = await executeAccountSwitch({
433
+ store,
434
+ storage,
435
+ sqlite,
436
+ paths,
437
+ targetAccount: targetAcc,
438
+ resolveStaleTokenAction: (issue, acc) => resolveStaleSwitchWithHealing(issue, acc, {
439
+ store,
440
+ storage,
441
+ sqlite,
442
+ executablePath: execPath,
443
+ interactive: true,
444
+ }),
445
+ onStep: (step, detail) => {
446
+ if (step === 'resolve') {
447
+ console.log(chalk.grey('✔ [0/4] 校验凭据形态与 OAuth 续期链路...'));
448
+ }
449
+ else if (step === 'close') {
450
+ if (detail === 'running') {
451
+ console.log(chalk.grey('✔ [1/4] 检测到 Cursor 运行中 -> 发送退出信号,释放 SQLite 独占锁'));
452
+ }
453
+ else {
454
+ console.log(chalk.grey('✔ [1/4] Cursor 未运行,无需关闭进程'));
455
+ }
456
+ }
457
+ else if (step === 'backup') {
458
+ console.log(chalk.grey('✔ [2/4] 创建本地安全快照备份 (storage.json 与 state.vscdb)'));
459
+ }
460
+ },
461
+ });
462
+ if (switchRes.aborted) {
463
+ console.log(chalk.yellow('已取消本次切号,本机 Cursor 登录状态与账号库未受任何改动。\n'));
464
+ await pressAnyKey();
465
+ return null;
373
466
  }
374
- else {
375
- console.log(chalk.grey('✔ [1/4] Cursor 未运行,无需关闭进程'));
376
- }
377
- // 2. 备份
378
- storage.createBackup();
379
- sqlite.createBackup();
380
- console.log(chalk.grey('✔ [2/4] 创建本地安全快照备份 (storage.json 与 state.vscdb)'));
381
- // 3. 换机器指纹
382
- const machineIds = targetAcc.machine_ids || generateMachineIds();
383
- storage.writeMachineIds(machineIds);
384
- console.log(chalk.grey(`✔ [3/4] 装载专属机器指纹: ${formatMachineIdSummary(machineIds)}`));
385
- // 4. 写 Token
386
- const token = TokenParser.extractTokenPart(targetAcc.token);
387
- const refreshToken = targetAcc.workos_cursor_session_token || token;
388
- storage.writeAuth(targetAcc.email, token, refreshToken);
389
- await sqlite.injectAuth(targetAcc.email, token, refreshToken);
390
- store.markCurrent(targetAcc.email);
391
- console.log(chalk.grey('✔ [4/4] 原子注入 Token 与认证状态到 SQLite 数据库'));
392
- console.log(chalk.green(`\n✔ 换号成功!当前账号: ${chalk.bold.white(targetAcc.email)}\n`));
467
+ if (switchRes.refreshed) {
468
+ console.log(chalk.green('✔ 已自动完成 OAuth Refresh Token 无感续期'));
469
+ }
470
+ console.log(chalk.grey(`✔ [3/4] 装载专属机器指纹 (JSON + SQLite + machineid): ${formatMachineIdSummary(switchRes.machineIds)}`));
471
+ if (switchRes.sidecarReport.authJsonUpdated || switchRes.sidecarReport.cliConfigUpdated) {
472
+ console.log(chalk.grey('✔ 已同步清理/更新 auth.json 与 cli-config.json 侧车凭据'));
473
+ }
474
+ for (const warn of switchRes.warnings) {
475
+ console.log(chalk.yellow(`! 提示: ${warn}`));
476
+ }
477
+ console.log(chalk.grey('✔ [4/4] 已清旧并原子注入 Token 与认证状态到 SQLite 数据库'));
478
+ console.log(chalk.green(`\n✔ 换号成功!当前账号: ${chalk.bold.white(switchRes.account.email)}\n`));
393
479
  let activeExecPath = execPath || findCursorExecutable();
394
480
  if (!activeExecPath) {
395
481
  const wantSpecify = await safeConfirm({
@@ -421,23 +507,22 @@ async function executeSwitchAccount(store, storage, sqlite, targetAcc, execPath)
421
507
  }
422
508
  }
423
509
  await pressAnyKey();
510
+ return switchRes.account;
424
511
  }
425
- /**
426
- * 添加账号子流程 (4大方式)
427
- */
428
512
  async function handleAddMenu(store, storage, sqlite, execPath) {
429
513
  const method = await quickSelect({
430
- message: '选择账号管理操作:',
514
+ header: chalk.bold.cyan('● 添加与管理账号'),
515
+ message: '账号管理:',
431
516
  choices: [
432
- { name: '1. 🌐 浏览器 OAuth 网页登录 (无痕新实例 · 官方秒级自动回传)', value: 'oauth', description: '调起全新独立无痕/隐私浏览器访问官网登录,官方秒级自动截获 Token 入库' },
433
- { name: '2. ⚡ 智能提取本机账号 (已有登录直接秒提入库)', value: 'smart_extract', description: '智能先测当前已登账号秒提,未登调起无痕浏览器 OAuth 登录' },
434
- { name: '3. 🔥 纯净云端代登 (海外住宅IP · 自动提取Token)', value: 'pure_login', description: '海外 S 级纯净住宅 IP 自动代登 / 自动收发验证码 / 提 Token 秒级入库' },
435
- { name: '4. 📋 粘贴 Token 快速录入', value: 'token', description: '直接粘贴 user_xxx::eyJ... 或 eyJ... 凭据快速入库' },
436
- { name: '5. 📁 批量文件导入', value: 'file', description: '从本地 accounts.json 文件批量解析并去重录入' },
517
+ { name: '1. 浏览器 OAuth 登录', value: 'oauth', description: '无痕浏览器登录并自动获取 Token' },
518
+ { name: '2. 提取本机账号', value: 'smart_extract', description: '读取本机登录或跳转浏览器登录' },
519
+ { name: '3. 纯净代登', value: 'pure_login', description: '通过代理环境辅助登录并获取 Token' },
520
+ { name: '4. 粘贴 Token 录入', value: 'token', description: '粘贴一段或三段凭据入库' },
521
+ { name: '5. 批量文件导入', value: 'file', description: '从本地文件批量导入并去重' },
437
522
  new Separator(),
438
- { name: '6. 🗑️ 清理/移除已有账号 (删除与批量管理)', value: 'cleanup', description: '单个精准删除、多选批量删除或一键清理已失效过期账号' },
523
+ { name: '6. 清理 / 删除账号', value: 'cleanup', description: '单选、多选删除或清理失效账号' },
439
524
  new Separator(),
440
- { name: '0. 返回主菜单', value: 'back', description: '取消并返回主界面' },
525
+ { name: '0. 返回', value: 'back', description: '返回主菜单' },
441
526
  ],
442
527
  pageSize: 12,
443
528
  });
@@ -463,14 +548,14 @@ async function handleAddMenu(store, storage, sqlite, execPath) {
463
548
  }
464
549
  if (method === 'token') {
465
550
  const rawInput = await safeInput({
466
- message: '请直接粘贴 Token (支持 user_xxx::eyJ... 或 eyJ...)',
551
+ message: '请粘贴一段 (user_xxx::eyJ... / eyJ...) 或三段打包串 (Access----Refresh----Web)',
467
552
  });
468
553
  if (!rawInput) {
469
554
  return;
470
555
  }
471
556
  const parsed = TokenParser.parse(rawInput);
472
557
  if (!parsed.isValid) {
473
- console.log(chalk.red('\n未识别到有效的 Token 格式,仅支持 user_xxx::eyJ... 或 eyJ... 格式。\n'));
558
+ console.log(chalk.red('\n未识别到有效的 Token 格式,支持一段 (user_xxx::eyJ... / eyJ...) 或三段打包串。\n'));
474
559
  }
475
560
  else {
476
561
  let email = parsed.email;
@@ -482,12 +567,16 @@ async function handleAddMenu(store, storage, sqlite, execPath) {
482
567
  });
483
568
  email = inputEmail || fallback;
484
569
  }
485
- store.addOrUpdate({
570
+ printFactualTokenStatus(parsed.token, parsed.refreshToken, parsed.workosSessionToken);
571
+ const ingestRes = await upgradeAccountWebTokenOnIngest({
486
572
  email,
487
573
  token: parsed.token,
574
+ refresh_token: parsed.refreshToken,
488
575
  workos_cursor_session_token: parsed.workosSessionToken,
489
576
  });
490
- console.log(chalk.green(`\n✔ 录入成功!账号 ${email} 已加入本地库\n`));
577
+ store.addOrUpdate(ingestRes.account);
578
+ printIngestUpgradeResult(ingestRes);
579
+ console.log(chalk.green(`\n✔ 录入成功!账号 ${email} 已加入本地库(${TokenParser.formatCredentialBadge(ingestRes.classification)})\n`));
491
580
  }
492
581
  }
493
582
  else if (method === 'file') {
@@ -516,18 +605,7 @@ async function handleAddMenu(store, storage, sqlite, execPath) {
516
605
  }
517
606
  }
518
607
  else {
519
- const lines = content.split('\n');
520
- for (const line of lines) {
521
- const parsed = TokenParser.parse(line);
522
- if (parsed.isValid && parsed.email) {
523
- store.addOrUpdate({
524
- email: parsed.email,
525
- token: parsed.token,
526
- workos_cursor_session_token: parsed.workosSessionToken,
527
- });
528
- count++;
529
- }
530
- }
608
+ count = importAccountsFromText(content, store);
531
609
  }
532
610
  console.log(chalk.green(`\n✔ 批量导入成功!共录入 ${count} 个有效账号\n`));
533
611
  }
@@ -538,9 +616,6 @@ async function handleAddMenu(store, storage, sqlite, execPath) {
538
616
  }
539
617
  await pressAnyKey();
540
618
  }
541
- /**
542
- * 账号清理与移除子菜单 (Account Cleanup & Management)
543
- */
544
619
  export async function handleAccountCleanupMenu(store, storage, sqlite) {
545
620
  while (true) {
546
621
  console.clear();
@@ -553,30 +628,14 @@ export async function handleAccountCleanupMenu(store, storage, sqlite) {
553
628
  }
554
629
  console.log(chalk.grey(`本地库当前共收录了 ${chalk.bold.white(accounts.length)} 个账号。\n`));
555
630
  const choice = await quickSelect({
556
- message: '请选择清理方式 (按数字秒选,按 0 返回):',
631
+ message: '账号清理:',
557
632
  choices: [
558
- {
559
- name: '1. 单个账号精准移除',
560
- value: 'single',
561
- description: '从列表中挑选指定账号,查看详情后安全移除',
562
- },
563
- {
564
- name: '2. 批量多选账号删除',
565
- value: 'batch',
566
- description: '使用空格键勾选多个账号,一键批量删除',
567
- },
568
- {
569
- name: '3. 一键清理已失效/已过期账号',
570
- value: 'expired',
571
- description: '智能扫描并批量清除所有标记为已失效或已过期的无效账号',
572
- },
573
- {
574
- name: '4. ⚠️ 清空全部账号 (高危重置)',
575
- value: 'clear_all',
576
- description: '清空本地 accounts.json 保存的所有账号信息 (需二次确认)',
577
- },
633
+ { name: '1. 删除单个账号', value: 'single', description: '挑选并删除指定账号' },
634
+ { name: '2. 批量勾选删除', value: 'batch', description: '多选批量删除账号' },
635
+ { name: '3. 清理失效 / 过期账号', value: 'expired', description: '清除所有已失效或过期账号' },
636
+ { name: '4. 清空全部账号', value: 'clear_all', description: '清空 accounts.json(需确认)' },
578
637
  new Separator(),
579
- { name: '0. 返回上一级', value: '__back__' },
638
+ { name: '0. 返回', value: '__back__' },
580
639
  ],
581
640
  });
582
641
  if (choice === '__back__' || !choice) {
@@ -728,7 +787,7 @@ async function handleCleanExpiredAccounts(store) {
728
787
  const expiredList = [];
729
788
  for (const acc of accounts) {
730
789
  if (acc.is_current) {
731
- continue; // 🛡️ 绝不误删当前本机正在激活的在用账号
790
+ continue;
732
791
  }
733
792
  if (acc.subscription_type === 'token_expired') {
734
793
  expiredList.push({ acc, reason: '官方标记凭据已失效 (Token Expired)' });
@@ -807,9 +866,6 @@ async function handleClearAllAccounts(store) {
807
866
  }
808
867
  await pressAnyKey();
809
868
  }
810
- /**
811
- * 账号搜索与匹配规则 (支持邮箱、别名、会员级别、中文计划名、到期状态)
812
- */
813
869
  function matchesAccount(acc, query) {
814
870
  const q = query.toLowerCase().trim();
815
871
  if (!q)
@@ -836,115 +892,22 @@ function matchesAccount(acc, query) {
836
892
  }
837
893
  return false;
838
894
  }
839
- /**
840
- * 复制 Token 专属子菜单
841
- */
842
- async function handleCopyTokenAction(email, currentToken, workosToken, machineIds) {
843
- const parsed = TokenParser.parse(currentToken);
844
- const jwtToken = parsed.token || currentToken;
845
- const sessionToken = workosToken || parsed.workosSessionToken;
846
- const choices = [];
847
- if (jwtToken) {
848
- choices.push({
849
- name: '1. 复制 Access Token (原生 Bearer JWT 凭据) [推荐]',
850
- value: 'jwt',
851
- description: '标准 Bearer JWT,适合各类第三方工具、VSCode 插件或 API 调用 (以 eyJ 开头)',
852
- });
853
- }
854
- if (sessionToken && sessionToken !== jwtToken) {
855
- choices.push({
856
- name: '2. 复制 WorkOS Session Token (网页 Session 凭据)',
857
- value: 'session',
858
- description: 'WorkOS Cookie 凭据,适合浏览器注入、官网免密登录及奥仔退款 (以 user_ 开头)',
859
- });
860
- }
861
- choices.push({
862
- name: sessionToken && sessionToken !== jwtToken ? '3. 一键复制完整账号配置 (JSON 格式)' : '2. 一键复制完整账号配置 (JSON 格式)',
863
- value: 'full',
864
- description: '复制包含邮箱、Token 和当前设备指纹的完整配置,便于备份或异地迁移',
865
- });
866
- choices.push({
867
- name: sessionToken && sessionToken !== jwtToken ? '4. 查看凭据完整明文 (终端打印)' : '3. 查看凭据完整明文 (终端打印)',
868
- value: 'view',
869
- description: '在终端屏幕上完整输出 Token 明文',
870
- });
871
- choices.push(new Separator());
872
- choices.push({ name: '0. 返回上一级', value: '__back__' });
873
- const pick = await quickSelect({
874
- message: `请选择要复制的凭据类型 [${email}]:`,
875
- choices,
895
+ async function handleCopyTokenAction(email, currentToken, workosToken, machineIds, refreshToken) {
896
+ await runInteractiveCopyAccountMenu({
897
+ email,
898
+ token: currentToken,
899
+ refresh_token: refreshToken,
900
+ workos_cursor_session_token: workosToken,
901
+ machine_ids: machineIds,
876
902
  });
877
- if (pick === '__back__' || !pick)
878
- return;
879
- if (pick === 'jwt') {
880
- const success = await copyToClipboard(jwtToken);
881
- console.log(boxen([
882
- chalk.bold.green('✔ Access Token 已成功复制到系统剪贴板!'),
883
- chalk.dim('────────────────────────────────────────────────'),
884
- ` 账号邮箱 : ${chalk.bold.white(email)}`,
885
- ` 凭据类型 : ${chalk.cyan('原生 Bearer JWT (Access Token)')}`,
886
- ` 凭据预览 : ${chalk.dim(jwtToken.slice(0, 16))}...${chalk.dim(jwtToken.slice(-12))} ${chalk.grey(`(共 ${jwtToken.length} 字符)`)}`,
887
- ` 操作提示 : ${chalk.yellow('已在剪贴板中,随时使用 Ctrl+V (或 Cmd+V) 粘贴即可')}`,
888
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
889
- if (!success) {
890
- console.log(chalk.yellow('提示: 自动写入剪贴板未生效,以下为 Token 明文,可手动选中复制:'));
891
- console.log(chalk.grey(jwtToken) + '\n');
892
- }
893
- await pressAnyKey();
894
- }
895
- else if (pick === 'session' && sessionToken) {
896
- const success = await copyToClipboard(sessionToken);
897
- console.log(boxen([
898
- chalk.bold.green('✔ WorkOS Session Token 已成功复制到系统剪贴板!'),
899
- chalk.dim('────────────────────────────────────────────────'),
900
- ` 账号邮箱 : ${chalk.bold.white(email)}`,
901
- ` 凭据类型 : ${chalk.cyan('WorkOS Session Token')}`,
902
- ` 凭据预览 : ${chalk.dim(sessionToken.slice(0, 20))}...${chalk.dim(sessionToken.slice(-12))} ${chalk.grey(`(共 ${sessionToken.length} 字符)`)}`,
903
- ` 操作提示 : ${chalk.yellow('已在剪贴板中,随时使用 Ctrl+V (或 Cmd+V) 粘贴即可')}`,
904
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
905
- if (!success) {
906
- console.log(chalk.yellow('提示: 自动写入剪贴板未生效,以下为 Token 明文,可手动选中复制:'));
907
- console.log(chalk.grey(sessionToken) + '\n');
908
- }
909
- await pressAnyKey();
910
- }
911
- else if (pick === 'full') {
912
- const fullText = JSON.stringify({
913
- email,
914
- token: jwtToken,
915
- workos_cursor_session_token: sessionToken,
916
- machine_ids: machineIds,
917
- }, null, 2);
918
- const success = await copyToClipboard(fullText);
919
- console.log(boxen([
920
- chalk.bold.green('✔ 账号完整配置已成功复制到系统剪贴板 (JSON 格式)!'),
921
- chalk.dim('────────────────────────────────────────────────'),
922
- ` 账号邮箱 : ${chalk.bold.white(email)}`,
923
- ` 操作提示 : ${chalk.yellow('直接使用 Ctrl + V (或 Cmd + V) 粘贴即可')}`,
924
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
925
- if (!success) {
926
- console.log(chalk.grey(fullText) + '\n');
927
- }
928
- await pressAnyKey();
929
- }
930
- else if (pick === 'view') {
931
- console.log(chalk.bold.cyan(`\n● 账号 ${email} 凭据明文详情:\n`));
932
- console.log(chalk.white('【Access Token (Bearer JWT)】:'));
933
- console.log(chalk.green(jwtToken) + '\n');
934
- if (sessionToken && sessionToken !== jwtToken) {
935
- console.log(chalk.white('【WorkOS Session Token】:'));
936
- console.log(chalk.cyan(sessionToken) + '\n');
937
- }
938
- await pressAnyKey();
939
- }
940
903
  }
941
- /**
942
- * 账号余量看板与实时检索流程
943
- */
944
904
  async function handleRadarMenu(store, storage, sqlite, execPath) {
945
905
  let currentFilter = 'default';
946
906
  let currentKeyword = '';
947
907
  while (true) {
908
+ if (process.stdout.isTTY) {
909
+ console.clear();
910
+ }
948
911
  const allAccounts = store.loadAll();
949
912
  let displayList = allAccounts;
950
913
  let subtitle = '';
@@ -966,7 +929,6 @@ async function handleRadarMenu(store, storage, sqlite, execPath) {
966
929
  subtitle = `${chalk.bold.white('全部账号列表')} ${chalk.grey(`(共 ${displayList.length} 个)`)}`;
967
930
  }
968
931
  else {
969
- // 默认精简视图:当前在用排在首位,展示前 15 条
970
932
  const sorted = [
971
933
  ...allAccounts.filter((a) => a.is_current),
972
934
  ...allAccounts.filter((a) => !a.is_current),
@@ -974,43 +936,47 @@ async function handleRadarMenu(store, storage, sqlite, execPath) {
974
936
  displayList = sorted.slice(0, 15);
975
937
  subtitle = `${chalk.bold.white('常用账号看板')} ${chalk.grey(`(展示前 ${displayList.length} 个,总计 ${allAccounts.length} 个)`)}`;
976
938
  }
939
+ const tableText = displayList.length > 0 ? renderAccountTable(displayList) : '';
977
940
  console.log(`\n${subtitle}`);
978
- if (displayList.length > 0) {
979
- console.log(renderAccountTable(displayList));
941
+ if (tableText) {
942
+ console.log(tableText);
980
943
  }
981
944
  else {
982
945
  console.log(chalk.yellow('\n 未找到任何匹配的账号,请尝试搜索其他关键词。\n'));
983
946
  }
947
+ const usedAboveRows = 3 + (tableText ? tableText.split(/\r?\n/).length : 3);
948
+ const radarMenuPageSize = Math.max(4, Math.min(12, (process.stdout.rows || 24) - usedAboveRows - 5));
984
949
  const actionChoices = [
985
- { name: '1. 搜索账号', value: 'search', description: '按邮箱关键词、域名如 @gmail 或会员类型筛选' },
986
- { name: '2. 仅看可用账号', value: 'active', description: '一键过滤已失效或已过期的无效账号' },
987
- { name: '3. 常用看板视图', value: 'default', description: '默认视图,展示当前在用及前 15 个常用账号' },
950
+ { name: '1. 搜索账号', value: 'search', description: '按邮箱、域名或套餐筛选' },
951
+ { name: '2. 仅看可用账号', value: 'active', description: '过滤失效和过期账号' },
952
+ { name: '3. 默认看板', value: 'default', description: '展示当前及前 15 个账号' },
988
953
  ];
989
954
  if (currentFilter !== 'all' && allAccounts.length > 15) {
990
- actionChoices.push({ name: `4. 查看全部列表 (${allAccounts.length} 个)`, value: 'all', description: '展示本地保存的所有账号完整表格' });
955
+ actionChoices.push({ name: `4. 查看全部 (${allAccounts.length})`, value: 'all', description: '展示全部本地账号' });
991
956
  }
992
957
  if (displayList.length > 0) {
993
958
  actionChoices.push(new Separator());
994
959
  if (displayList.length <= 50) {
995
- actionChoices.push({ name: '5. 切换列表中账号', value: 'switch_from_list', description: '直接从当前展示的列表中挑选账号一键切换' });
996
- actionChoices.push({ name: '6. 复制列表中账号 Token', value: 'copy_from_list', description: '从列表中挑选账号,一键复制其 Access Token 或 WorkOS 凭据' });
997
- actionChoices.push({ name: '7. 打开官网控制台', value: 'dash_from_list', description: '免密直达当前列表中选定账号的网页后台' });
998
- actionChoices.push({ name: '8. 打开 Outlook 邮箱', value: 'mail_from_list', description: '独立隔离浏览器自动登录当前列表中选定账号的 Outlook 邮箱' });
960
+ actionChoices.push({ name: '5. 切换账号', value: 'switch_from_list', description: '从当前列表选号切换' });
961
+ actionChoices.push({ name: '6. 复制 Token', value: 'copy_from_list', description: '复制 Access 或 WorkOS 凭据' });
962
+ actionChoices.push({ name: '7. 打开控制台', value: 'dash_from_list', description: '免密打开网页后台' });
963
+ actionChoices.push({ name: '8. 打开 Outlook 邮箱', value: 'mail_from_list', description: '自动登录对应邮箱' });
999
964
  }
1000
- actionChoices.push({ name: '9. 🗑️ 账号清理与移除', value: 'cleanup_from_list', description: '从列表中移除指定账号、多选批量删除或一键清理失效账号' });
965
+ actionChoices.push({ name: '9. 清理账号', value: 'cleanup_from_list', description: '删除或批量清理账号' });
1001
966
  }
1002
967
  actionChoices.push(new Separator());
1003
- actionChoices.push({ name: '0. 返回主菜单', value: 'back', description: '返回主界面' });
968
+ actionChoices.push({ name: '0. 返回', value: 'back', description: '返回主菜单' });
1004
969
  let action;
1005
970
  try {
1006
971
  action = await quickSelect({
1007
972
  message: '看板操作:',
1008
973
  choices: actionChoices,
1009
- pageSize: 12,
974
+ pageSize: radarMenuPageSize,
1010
975
  });
1011
976
  }
1012
977
  catch (err) {
1013
978
  if (err?.name === 'ExitPromptError') {
979
+ leaveAltScreenIfActive();
1014
980
  process.stdout.write('\x1b[?25h\n');
1015
981
  process.exit(0);
1016
982
  }
@@ -1081,7 +1047,7 @@ async function handleRadarMenu(store, storage, sqlite, execPath) {
1081
1047
  if (pickEmail !== '__back__' && pickEmail) {
1082
1048
  const target = displayList.find((a) => a.email === pickEmail);
1083
1049
  if (target) {
1084
- await handleCopyTokenAction(target.email, target.token, target.workos_cursor_session_token, target.machine_ids);
1050
+ await handleCopyTokenAction(target.email, target.token, target.workos_cursor_session_token, target.machine_ids, target.refresh_token);
1085
1051
  }
1086
1052
  }
1087
1053
  }
@@ -1145,9 +1111,6 @@ async function handleRadarMenu(store, storage, sqlite, execPath) {
1145
1111
  }
1146
1112
  }
1147
1113
  }
1148
- /**
1149
- * 官网后台快捷交互 (支持直接录入 Token 免密直达)
1150
- */
1151
1114
  async function handleDashboardMenu(store, currentAcc) {
1152
1115
  const accounts = store.loadAll();
1153
1116
  if (accounts.length === 0) {
@@ -1161,22 +1124,24 @@ async function handleDashboardMenu(store, currentAcc) {
1161
1124
  }
1162
1125
  return;
1163
1126
  }
1164
- // 优先把当前在用的账号排在前面
1165
1127
  const sortedAccounts = [
1166
1128
  ...accounts.filter((a) => a.is_current),
1167
1129
  ...accounts.filter((a) => !a.is_current),
1168
1130
  ];
1169
1131
  let targetAcc;
1170
1132
  while (true) {
1133
+ if (process.stdout.isTTY) {
1134
+ console.clear();
1135
+ }
1171
1136
  const choices = [
1172
- { name: '0. 返回主菜单', value: '__back__' },
1137
+ { name: '0. 返回', value: '__back__' },
1173
1138
  {
1174
- name: 't. 录入 Token 免密直达...',
1139
+ name: 't. 录入 Token 直达',
1175
1140
  value: '__token_dash__',
1176
1141
  key: 't',
1177
- description: '直接粘贴 user_xxx:: 或 eyJ... 凭据,秒级调起浏览器并免密直达控制台',
1142
+ description: '粘贴凭据直接打开网页控制台',
1178
1143
  },
1179
- { name: 's. 搜索账号...', value: '__search__', key: 's', description: '输入关键词搜索指定账号' },
1144
+ { name: 's. 搜索账号', value: '__search__', key: 's', description: '按邮箱搜索账号' },
1180
1145
  new Separator(),
1181
1146
  ];
1182
1147
  sortedAccounts.forEach((acc, index) => {
@@ -1185,11 +1150,12 @@ async function handleDashboardMenu(store, currentAcc) {
1185
1150
  choices.push({
1186
1151
  name: `${index + 1}. ${plan}${acc.email}${isCurrent}`,
1187
1152
  value: acc.email,
1188
- description: `免密直达 ${acc.email} 的 Cursor 网页后台 (Dashboard)`,
1153
+ description: `打开 ${acc.email} 的 Cursor 网页后台`,
1189
1154
  });
1190
1155
  });
1191
1156
  const chosenEmail = await quickSelect({
1192
- message: '选择需要打开官网控制台的账号 (直接按序号直达,按 t 录入Token,按 0 返回):',
1157
+ header: chalk.bold.cyan('● 用 Token 打开 Cursor 官网控制台'),
1158
+ message: '选择账号 (序号 / t / s / 0):',
1193
1159
  choices,
1194
1160
  pageSize: 12,
1195
1161
  });
@@ -1243,9 +1209,6 @@ async function handleDashboardMenu(store, currentAcc) {
1243
1209
  await DashboardLauncher.openDashboard(targetAcc);
1244
1210
  await pressAnyKey();
1245
1211
  }
1246
- /**
1247
- * 录入 Token 免密直达 Cursor 官网控制台
1248
- */
1249
1212
  async function handleTokenDirectDashboard(store) {
1250
1213
  console.clear();
1251
1214
  console.log(chalk.bold.cyan('\n● 录入 Token 免密直达官网控制台 (Token Direct Dashboard)\n'));
@@ -1259,7 +1222,7 @@ async function handleTokenDirectDashboard(store) {
1259
1222
  const rawToken = rawInput.trim();
1260
1223
  const parsed = TokenParser.parse(rawToken);
1261
1224
  if (!parsed.isValid) {
1262
- console.log(chalk.red('\n未识别到有效的 Token 格式,仅支持 user_xxx:: 或 eyJ... 格式。\n'));
1225
+ console.log(chalk.red('\n未识别到有效的 Token 格式,支持一段 (user_xxx:: / eyJ...) 或三段打包串。\n'));
1263
1226
  await pressAnyKey();
1264
1227
  return;
1265
1228
  }
@@ -1278,34 +1241,26 @@ async function handleTokenDirectDashboard(store) {
1278
1241
  if (!email) {
1279
1242
  email = `token_user_${Date.now().toString().slice(-4)}@cursor.sh`;
1280
1243
  }
1281
- // 同步会员与用量信息
1282
1244
  const usageRes = await OfficialApiClient.fetchUsage(parsed.token);
1283
1245
  const existing = store.getByEmail(email);
1284
- const subType = usageRes.success && usageRes.subscriptionType
1285
- ? usageRes.subscriptionType
1286
- : existing?.subscription_type || 'free';
1287
- console.log(chalk.green(`✔ ${email} [${formatPlanName(subType)}]`));
1288
- const targetAcc = {
1246
+ const targetAcc = applyParsedCredentialToAccount({
1247
+ parsed,
1289
1248
  email,
1290
- token: parsed.token,
1291
- workos_cursor_session_token: parsed.workosSessionToken || parsed.token,
1292
- subscription_type: subType,
1293
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
1294
- machine_ids: existing?.machine_ids || generateMachineIds(),
1295
- };
1296
- // 顺便录入本地账号库(若尚未保存)
1249
+ existing,
1250
+ usageRes,
1251
+ machineIds: existing?.machine_ids || generateMachineIds(),
1252
+ fallbackWorkosToToken: true,
1253
+ });
1254
+ console.log(chalk.green(`✔ ${email} [${formatPlanName(targetAcc.subscription_type)}]`));
1297
1255
  if (!existing) {
1298
1256
  store.addOrUpdate(targetAcc);
1299
1257
  console.log(chalk.grey('✔ 已自动纳管录入本地多账号库,便于日后极速切换'));
1300
1258
  }
1301
- await copyToClipboard(targetAcc.token);
1259
+ await copyPreferredAccountCredential(targetAcc);
1302
1260
  console.log(chalk.cyan(`\n正在调起全新独立浏览器并免密直达 Cursor 控制台 (${targetAcc.email})...`));
1303
1261
  await DashboardLauncher.openDashboard(targetAcc);
1304
1262
  await pressAnyKey();
1305
1263
  }
1306
- /**
1307
- * 打开 Outlook 邮箱交互式菜单
1308
- */
1309
1264
  async function handleOutlookMailMenu(store, currentAcc) {
1310
1265
  while (true) {
1311
1266
  console.clear();
@@ -1316,22 +1271,22 @@ async function handleOutlookMailMenu(store, currentAcc) {
1316
1271
  const choices = [];
1317
1272
  if (currentEmail) {
1318
1273
  const hasPwd = Boolean(currentAcc?.email_password);
1319
- const pwdTag = hasPwd ? chalk.green('[已存密码]') : chalk.yellow('[未存密码]');
1274
+ const pwdTag = hasPwd ? chalk.green('[有密码]') : chalk.yellow('[无密码]');
1320
1275
  choices.push({
1321
- name: `1. 当前在用账号直接打开: ${chalk.bold.white(currentEmail)} ${pwdTag}`,
1276
+ name: `1. 当前账号: ${chalk.bold.white(currentEmail)} ${pwdTag}`,
1322
1277
  value: '__current__',
1323
- description: hasPwd ? '使用已保存的邮箱密码直接自动登录' : '当前账号未保存邮箱密码,可直接打开并在网页中输入',
1278
+ description: hasPwd ? '使用已存密码自动登录' : '无密码,打开后手动登录',
1324
1279
  });
1325
1280
  }
1326
1281
  choices.push({
1327
- name: `2. 从本地已保存账号列表中选择 (${accounts.length} 个账号)`,
1282
+ name: `2. 从账号列表选择 (${accounts.length})`,
1328
1283
  value: '__select__',
1329
- description: '从本地已纳管多账号库中挑选一个账号打开独立邮箱窗口',
1284
+ description: '从本地账号中选择并打开邮箱',
1330
1285
  }, {
1331
- name: '3. 临时录入邮箱与密码打开 (不存库)',
1286
+ name: '3. 临时输入邮箱密码',
1332
1287
  value: '__manual__',
1333
- description: '支持直接粘贴 email----password 临时调起独立浏览器,即开即走',
1334
- }, new Separator(), { name: '0. 返回上一级主菜单', value: '__back__' });
1288
+ description: '粘贴 email----password 临时打开',
1289
+ }, new Separator(), { name: '0. 返回', value: '__back__' });
1335
1290
  let pick;
1336
1291
  try {
1337
1292
  pick = await quickSelect({
@@ -1422,7 +1377,7 @@ async function handleOutlookMailMenu(store, currentAcc) {
1422
1377
  }
1423
1378
  console.log(chalk.cyan(`\n正在调起全新独立浏览器并自动登录 ${email}...`));
1424
1379
  if (openDashboard && cursorToken) {
1425
- console.log(chalk.green(` [联动] 同时在浏览器新标签页免密打开 Cursor 控制台 (Token: ${cursorToken.slice(0, 15)}...)`));
1380
+ console.log(chalk.green(` [联动] 同时在浏览器新标签页免密打开 Cursor 控制台 (Token: ${maskToken(cursorToken)})`));
1426
1381
  }
1427
1382
  const res = await OutlookLauncher.openMailbox({
1428
1383
  email,
@@ -1487,9 +1442,6 @@ async function executeMailboxOpen(store, account) {
1487
1442
  OutlookLauncher.printResultCard(res);
1488
1443
  await pressAnyKey();
1489
1444
  }
1490
- /**
1491
- * 官方 PKCE OAuth 网页登录流程 (独立无痕浏览器实例 + 官方端点秒级自动回传)
1492
- */
1493
1445
  async function handleOfficialOAuthAction(store, storage, sqlite, execPath) {
1494
1446
  const result = await OAuthReceiver.startOfficialOAuthFlow();
1495
1447
  if (!result.success || !result.accessToken) {
@@ -1499,7 +1451,6 @@ async function handleOfficialOAuthAction(store, storage, sqlite, execPath) {
1499
1451
  await pressAnyKey();
1500
1452
  return;
1501
1453
  }
1502
- // 1. 邮箱确认 (优先使用官方 RPC 接口精准查询到的邮箱)
1503
1454
  let email = result.email;
1504
1455
  if (!email) {
1505
1456
  const fallback = result.authId
@@ -1511,36 +1462,27 @@ async function handleOfficialOAuthAction(store, storage, sqlite, execPath) {
1511
1462
  });
1512
1463
  email = inputEmail || fallback;
1513
1464
  }
1514
- // 2. 生成全新独立硬件指纹 (确保多账号隔离防封)
1515
1465
  const machineIds = generateMachineIds();
1516
- // 3. 官方同步用量与会员订阅
1517
1466
  process.stdout.write(chalk.grey('\n正在向 Cursor 官方同步高速用量与订阅计划... '));
1518
1467
  const usageRes = await OfficialApiClient.fetchUsage(result.accessToken);
1519
1468
  const existing = store.getByEmail(email);
1520
- const subType = usageRes.success && usageRes.subscriptionType
1521
- ? usageRes.subscriptionType
1522
- : existing?.subscription_type || 'free';
1523
- console.log(chalk.green(`✔ ${formatPlanName(subType)}`));
1524
- // 4. 入库保存
1525
- const newAccount = {
1469
+ const newAccount = buildOAuthAccountInfo({
1526
1470
  email,
1527
- token: result.accessToken,
1528
- workos_cursor_session_token: result.refreshToken || result.accessToken,
1529
- subscription_type: subType,
1530
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
1531
- machine_ids: machineIds,
1532
- };
1471
+ accessToken: result.accessToken,
1472
+ refreshToken: result.refreshToken,
1473
+ authId: result.authId,
1474
+ usageRes,
1475
+ existing,
1476
+ machineIds,
1477
+ });
1478
+ console.log(chalk.green(`✔ ${formatPlanName(newAccount.subscription_type)}`));
1533
1479
  store.addOrUpdate(newAccount);
1534
- const copied = await copyToClipboard(newAccount.token);
1535
- console.log(boxen([
1536
- chalk.bold.green('🎉 官方 OAuth 登录成功!账号已自动收录入库'),
1537
- chalk.dim('────────────────────────────────────────────────'),
1538
- ` 登录邮箱 : ${chalk.bold.white(newAccount.email)}`,
1539
- ` 会员级别 : ${formatPlanBadge(newAccount.subscription_type)}`,
1540
- ` 专属指纹 : ${chalk.cyan(formatMachineIdSummary(machineIds))} ${chalk.dim('(独立隔离防封)')}`,
1541
- ` 官方凭据 : ${chalk.grey(newAccount.token.slice(0, 16))}...[已加密归档]`,
1542
- ` 系统剪贴板: ${copied ? chalk.green('✔ Token 已自动复制到系统剪贴板 (可直接粘贴)') : chalk.yellow('○ 请手动复制')}`,
1543
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
1480
+ await printExtractedCredentialsResult({
1481
+ header: '🎉 官方 OAuth 登录成功!账号已自动收录入库',
1482
+ account: newAccount,
1483
+ machineIds,
1484
+ showPlaintext: false,
1485
+ });
1544
1486
  const doSwitch = await safeConfirm({
1545
1487
  message: `是否立即切换到该账号 (${newAccount.email}) 并激活专属指纹?`,
1546
1488
  default: true,
@@ -1552,22 +1494,20 @@ async function handleOfficialOAuthAction(store, storage, sqlite, execPath) {
1552
1494
  await pressAnyKey();
1553
1495
  }
1554
1496
  }
1555
- /**
1556
- * 浏览器提取 Token 流程 (Browser Token Extractor)
1557
- * 核心哲学:调起浏览器截获官方 Token;若本机 IDE 已登则自动免密秒提,免去开浏览器。
1558
- */
1559
1497
  async function handleSmartExtractAction(store, storage, sqlite, execPath) {
1560
1498
  console.clear();
1561
1499
  console.log(chalk.bold.cyan('\n● 浏览器提取 Token (Browser Token Extractor)\n'));
1562
1500
  process.stdout.write(chalk.cyan('正在智能探测本机 Cursor 登录凭据... '));
1563
- const currentEmail = storage.readCurrentEmail() || (await sqlite.readEmail());
1564
- const currentToken = storage.readCurrentToken() || (await sqlite.readToken());
1565
- // 1. 如果本机已检测到登录态:
1501
+ const localAuth = await readLocalCursorAuth(storage, sqlite);
1502
+ const currentEmail = localAuth.email;
1503
+ const currentToken = localAuth.token;
1504
+ if (!currentToken && localAuth.isEncrypted && localAuth.encryptionError) {
1505
+ console.log(chalk.yellow(`\n! 本地检测到新版 safeStorage 加密凭据但解密失败: ${localAuth.encryptionError}`));
1506
+ }
1566
1507
  if (currentEmail && currentToken) {
1567
1508
  console.log(chalk.green('✔ 已发现已登账号 (免开浏览器!)\n'));
1568
1509
  const currentMachineIds = storage.readMachineIds();
1569
1510
  const existing = store.getByEmail(currentEmail);
1570
- // 查询官方会员与额度状态
1571
1511
  let subscriptionType = existing?.subscription_type;
1572
1512
  let currentPeriodUsage = existing?.current_period_usage;
1573
1513
  try {
@@ -1605,38 +1545,39 @@ async function handleSmartExtractAction(store, storage, sqlite, execPath) {
1605
1545
  ` 本地状态 : ${isSaved ? chalk.green('● 已保存在本地库 (在用中)') : chalk.yellow('○ 尚未归档入库')}`,
1606
1546
  ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
1607
1547
  const nextChoice = await quickSelect({
1608
- message: '请选择后续操作 (按数字秒选,按 0 返回):',
1548
+ message: '选择操作:',
1609
1549
  choices: [
1610
1550
  {
1611
- name: '1. 复制该账号 Token (一键拷贝到系统剪贴板)',
1551
+ name: '1. 复制 Token',
1612
1552
  value: 'copy_token',
1613
- description: '快速将 Access Token 或 WorkOS Session Token 复制到系统剪贴板',
1553
+ description: '复制 Access 或 WorkOS Token 到剪贴板',
1614
1554
  },
1615
1555
  {
1616
- name: isSaved ? '2. 刷新该账号官方额度与用量数据' : '2. 立即将该账号收录入库',
1556
+ name: isSaved ? '2. 刷新额度与用量' : '2. 保存到本地账号库',
1617
1557
  value: 'save_or_refresh',
1618
- description: isSaved ? '重新向 Cursor 官方同步最新高速请求余量与订阅周期' : '将当前检测到的账号及硬件指纹永久归档保存至本地库',
1558
+ description: isSaved ? '同步最新额度与订阅周期' : '保存账号与设备指纹到本地',
1619
1559
  },
1620
1560
  {
1621
- name: '3. 打开浏览器登录,录入另一个新账号',
1561
+ name: '3. 浏览器登录新账号',
1622
1562
  value: 'browser_new',
1623
- description: '调起浏览器访问 Cursor 官网,登录或截获另一个账号的 Token',
1563
+ description: '打开浏览器登录提取其他账号',
1624
1564
  },
1625
1565
  new Separator(),
1626
- { name: '0. 返回主菜单', value: '__back__' },
1566
+ { name: '0. 返回', value: '__back__' },
1627
1567
  ],
1628
1568
  });
1629
1569
  if (nextChoice === '__back__' || !nextChoice) {
1630
1570
  return;
1631
1571
  }
1632
1572
  if (nextChoice === 'copy_token') {
1633
- await handleCopyTokenAction(currentEmail, currentToken, existing?.workos_cursor_session_token, currentMachineIds);
1573
+ await handleCopyTokenAction(currentEmail, currentToken, existing?.workos_cursor_session_token, currentMachineIds, localAuth.refreshToken || existing?.refresh_token);
1634
1574
  continue;
1635
1575
  }
1636
1576
  if (nextChoice === 'save_or_refresh') {
1637
1577
  const accObj = {
1638
1578
  email: currentEmail,
1639
1579
  token: currentToken,
1580
+ refresh_token: localAuth.refreshToken || existing?.refresh_token,
1640
1581
  workos_cursor_session_token: existing?.workos_cursor_session_token,
1641
1582
  machine_ids: currentMachineIds,
1642
1583
  subscription_type: subscriptionType || existing?.subscription_type || 'free',
@@ -1657,24 +1598,23 @@ async function handleSmartExtractAction(store, storage, sqlite, execPath) {
1657
1598
  else {
1658
1599
  console.log(chalk.yellow('○ 本机未登录,将直接调起浏览器打开官网进行登录提取...\n'));
1659
1600
  }
1660
- // 2. 本机未登录,或者用户明确选择录入另一个新账号:
1661
1601
  console.clear();
1662
1602
  console.log(chalk.bold.cyan('\n● 浏览器提取与录入 Token (Browser Token Extractor)\n'));
1663
1603
  const extractChoice = await quickSelect({
1664
- message: '选择新账号录入方式 (按数字秒选,按 0 返回):',
1604
+ message: '提取方式:',
1665
1605
  choices: [
1666
1606
  {
1667
- name: '1. 🌐 浏览器 OAuth 网页登录 (无痕新实例 · 官方秒级自动回传)',
1607
+ name: '1. 浏览器 OAuth 登录',
1668
1608
  value: 'oauth',
1669
- description: '调起全新独立无痕/隐私浏览器访问官网登录,官方秒级自动截获 Token 入库',
1609
+ description: '无痕浏览器登录并自动截获 Token',
1670
1610
  },
1671
1611
  {
1672
- name: '2. 📋 手动粘贴 Token 凭据录入',
1612
+ name: '2. 手动粘贴 Token',
1673
1613
  value: 'paste',
1674
- description: '直接粘贴 user_xxx::eyJ... 或 eyJ... 凭据快速入库',
1614
+ description: '粘贴 user_xxx:: 或 eyJ... 凭据入库',
1675
1615
  },
1676
1616
  new Separator(),
1677
- { name: '0. 返回上一级', value: '__back__' },
1617
+ { name: '0. 返回', value: '__back__' },
1678
1618
  ],
1679
1619
  });
1680
1620
  if (extractChoice === '__back__' || !extractChoice) {
@@ -1684,13 +1624,12 @@ async function handleSmartExtractAction(store, storage, sqlite, execPath) {
1684
1624
  await handleOfficialOAuthAction(store, storage, sqlite, execPath);
1685
1625
  return;
1686
1626
  }
1687
- // 手动粘贴流程
1688
1627
  console.log(chalk.white('\n💡 获取 Token 方式(任选其一,均可直接粘贴):'));
1689
1628
  console.log(chalk.grey(' • 方式 1: 浏览器登录后,在个人设置或 Cookie 复制 user_xxx:: 或 eyJ... 凭据'));
1690
- console.log(chalk.grey(' • 方式 2: 如已有其他账号的官方凭据,亦可在此直接粘贴录入\n'));
1629
+ console.log(chalk.grey(' • 方式 2: 支持直接粘贴三段完整凭据串 (Access----Refresh----Web)\n'));
1691
1630
  console.log(chalk.grey(' (输入 0 或按回车取消返回)\n'));
1692
1631
  const rawInput = await safeInput({
1693
- message: '请在此粘贴 Token 凭据 (支持 user_xxx:: 或 eyJ... 格式):',
1632
+ message: '请在此粘贴凭据 (支持一段 user_xxx:: / eyJ... 或三段打包串):',
1694
1633
  });
1695
1634
  if (!rawInput || rawInput.trim() === '0' || rawInput.trim().toLowerCase() === 'q') {
1696
1635
  console.log(chalk.grey('\n已取消提取操作,正在返回...\n'));
@@ -1700,7 +1639,7 @@ async function handleSmartExtractAction(store, storage, sqlite, execPath) {
1700
1639
  const rawToken = rawInput.trim();
1701
1640
  const parsed = TokenParser.parse(rawToken);
1702
1641
  if (!parsed.isValid) {
1703
- console.log(chalk.red('\n未识别到有效的 Token 格式,仅支持 user_xxx:: 或 eyJ... 格式。\n'));
1642
+ console.log(chalk.red('\n未识别到有效的 Token 格式,支持一段 (user_xxx:: / eyJ...) 或三段打包串。\n'));
1704
1643
  await pressAnyKey();
1705
1644
  return;
1706
1645
  }
@@ -1710,25 +1649,25 @@ async function handleSmartExtractAction(store, storage, sqlite, execPath) {
1710
1649
  const fallbackEmail = parsed.sub ? `${parsed.sub.replace('auth0|', '')}@cursor.sh` : `account_${Date.now().toString().slice(-6)}@cursor.sh`;
1711
1650
  const email = parsed.email || fallbackEmail;
1712
1651
  const existing = store.getByEmail(email);
1713
- const newAccount = {
1652
+ const draftAccount = applyParsedCredentialToAccount({
1653
+ parsed,
1714
1654
  email,
1715
- token: rawToken,
1716
- workos_cursor_session_token: parsed.workosSessionToken || rawToken,
1717
- subscription_type: usageRes.success && usageRes.subscriptionType ? usageRes.subscriptionType : (existing?.subscription_type || 'free'),
1718
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
1719
- machine_ids: machineIds,
1720
- };
1655
+ existing,
1656
+ usageRes,
1657
+ machineIds,
1658
+ fallbackWorkosToToken: true,
1659
+ });
1660
+ printFactualTokenStatus(draftAccount.token, draftAccount.refresh_token, draftAccount.workos_cursor_session_token);
1661
+ const ingestRes = await upgradeAccountWebTokenOnIngest(draftAccount);
1662
+ const newAccount = ingestRes.account;
1721
1663
  store.addOrUpdate(newAccount);
1722
- const copied = await copyToClipboard(newAccount.token);
1723
- console.log(boxen([
1724
- chalk.bold.green('✔ 账号 Token 录入成功!已加入本地多账号库'),
1725
- chalk.dim('────────────────────────────────────────────────'),
1726
- ` 登录邮箱 : ${chalk.bold.white(newAccount.email)}`,
1727
- ` 会员级别 : ${formatPlanBadge(newAccount.subscription_type)}`,
1728
- ` 专属指纹 : ${chalk.cyan(formatMachineIdSummary(machineIds))}`,
1729
- ` 官方凭据 : ${chalk.grey(rawToken.slice(0, 16))}...[已加密保护]`,
1730
- ` 系统剪贴板: ${copied ? chalk.green('✔ Token 已自动复制到系统剪贴板 (可直接粘贴)') : chalk.yellow('○ 请手动复制')}`,
1731
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
1664
+ printIngestUpgradeResult(ingestRes);
1665
+ await printExtractedCredentialsResult({
1666
+ header: '✔ 账号 Token 录入成功!已加入本地多账号库',
1667
+ account: newAccount,
1668
+ machineIds,
1669
+ showPlaintext: false,
1670
+ });
1732
1671
  const doSwitch = await safeConfirm({
1733
1672
  message: `是否立即切换到该账号 (${newAccount.email}) 并激活专属指纹?`,
1734
1673
  default: true,
@@ -1740,19 +1679,13 @@ async function handleSmartExtractAction(store, storage, sqlite, execPath) {
1740
1679
  await pressAnyKey();
1741
1680
  }
1742
1681
  }
1743
- /**
1744
- * 兼容性别名
1745
- */
1746
1682
  async function handleBrowserTokenAction(store, storage, sqlite, execPath) {
1747
1683
  return handleSmartExtractAction(store, storage, sqlite, execPath);
1748
1684
  }
1749
1685
  async function handleCaptureAction(store, storage, sqlite) {
1750
1686
  return handleSmartExtractAction(store, storage, sqlite);
1751
1687
  }
1752
- /**
1753
- * 机器指纹管理
1754
- */
1755
- async function handleFingerprintMenu(storage, currentAcc) {
1688
+ async function handleFingerprintMenu(storage, currentAcc, sqlite) {
1756
1689
  const currentIds = storage.readMachineIds();
1757
1690
  console.log(chalk.bold.cyan('\n当前设备硬件指纹详情:'));
1758
1691
  console.log(chalk.grey(`• devDeviceId : ${chalk.white(currentIds['telemetry.devDeviceId'] || '--')}`));
@@ -1760,23 +1693,35 @@ async function handleFingerprintMenu(storage, currentAcc) {
1760
1693
  console.log(chalk.grey(`• macMachineId : ${chalk.white(maskToken(currentIds['telemetry.macMachineId']))}`));
1761
1694
  console.log(chalk.grey(`• machineId : ${chalk.white(maskToken(currentIds['telemetry.machineId']))}\n`));
1762
1695
  const fpAction = await quickSelect({
1763
- message: '选择指纹操作 (按数字秒选,按 0 返回):',
1696
+ message: '指纹操作:',
1764
1697
  choices: [
1765
- { name: '1. 重置随机硬件码', value: 'reset', description: '生成全套崭新随机硬件指纹,彻底解除封号风控关联' },
1766
- { name: '2. 备份当前硬件码', value: 'backup', description: '创建当前指纹配置安全快照' },
1698
+ { name: '1. 重置随机指纹', value: 'reset', description: '生成全新随机设备指纹' },
1699
+ { name: '2. 备份当前指纹', value: 'backup', description: '创建当前指纹快照' },
1767
1700
  new Separator(),
1768
- { name: '0. 返回主菜单', value: 'back', description: '返回主界面' },
1701
+ { name: '0. 返回', value: 'back' },
1769
1702
  ],
1770
1703
  });
1771
1704
  if (fpAction === 'back') {
1772
1705
  return;
1773
1706
  }
1774
1707
  if (fpAction === 'reset') {
1708
+ const paths = resolveCursorPaths();
1709
+ const activeSqlite = sqlite || new SqliteBridge(paths.sqliteDb);
1775
1710
  const newIds = generateMachineIds();
1776
1711
  storage.createBackup();
1777
- storage.writeMachineIds(newIds);
1778
- console.log(chalk.green('\n✔ 机器指纹已重置为全套随机硬件码!旧指纹已安全备份。'));
1779
- console.log(chalk.grey(`新 devDeviceId: ${newIds['telemetry.devDeviceId']}\n`));
1712
+ activeSqlite.createBackup();
1713
+ const applied = await applyMachineIdsToCursor({
1714
+ storage,
1715
+ sqlite: activeSqlite,
1716
+ paths,
1717
+ machineIds: newIds,
1718
+ });
1719
+ console.log(chalk.green('\n✔ 机器指纹已全链路重置为全套随机硬件码!旧指纹已安全备份。'));
1720
+ console.log(chalk.grey(`新 devDeviceId: ${newIds['telemetry.devDeviceId']}`));
1721
+ if (applied.sidecarReport.machineIdFileUpdated) {
1722
+ console.log(chalk.grey(`已同步更新 ${paths.machineIdFile}`));
1723
+ }
1724
+ console.log('');
1780
1725
  }
1781
1726
  else if (fpAction === 'backup') {
1782
1727
  const backupPath = storage.createBackup();
@@ -1784,9 +1729,6 @@ async function handleFingerprintMenu(storage, currentAcc) {
1784
1729
  }
1785
1730
  await pressAnyKey();
1786
1731
  }
1787
- /**
1788
- * 备份操作
1789
- */
1790
1732
  async function handleBackupAction(storage, sqlite) {
1791
1733
  const b1 = storage.createBackup();
1792
1734
  const b2 = sqlite.createBackup();
@@ -1795,42 +1737,39 @@ async function handleBackupAction(storage, sqlite) {
1795
1737
  console.log(chalk.grey(`• sqlite 备份 : ${b2}\n`));
1796
1738
  await pressAnyKey();
1797
1739
  }
1798
- /**
1799
- * 奥仔退款 (席位刷新/重置额度) 交互子流程 (极简智能引导版)
1800
- */
1801
1740
  async function handleRefundMenu(store, currentAcc) {
1802
1741
  const refundService = new RefundService();
1803
1742
  const config = refundService.getConfigStore();
1804
1743
  let cardCode = config.getSeatCardCode();
1805
1744
  let cachedAuthInfo = null;
1745
+ let lastAuthError = '';
1806
1746
  let lastVerifiedCard = '';
1807
- // 1. 如果尚未绑定卡密:主动向导,一步到位,绝不让用户在无用菜单中迷失
1808
1747
  if (!cardCode) {
1809
1748
  console.clear();
1810
1749
  console.log(boxen([
1811
- `${chalk.bold.cyan('CURSOR-SWITCH')} ${chalk.dim('●')} ${chalk.bold.white('奥仔席位退款服务')}`,
1812
- chalk.dim('────────────────────────────────────────────────'),
1813
- '首次使用,请输入您的奥仔席位卡密开启退款服务。',
1814
- chalk.dim('• 本地安全 : 仅保存于本地 ~/.cursor-switch/config.json'),
1815
- chalk.dim('• 取消方式 : 输入 0、q 或直接按回车可取消返回'),
1750
+ `${chalk.bold.cyan('CURSOR-SWITCH')} ${chalk.dim('●')} ${chalk.bold.white('Cursor 退款服务')}`,
1751
+ chalk.dim('────────────────────────────────────────────────────────'),
1752
+ '请输入退款卡密(与 getdoubao.com 通用)。',
1753
+ chalk.dim('• 失败保障 : 退款失败点数自动退还'),
1754
+ chalk.dim('• 取消返回 : 输入 0、q 或直接按回车'),
1816
1755
  ].join('\n'), {
1817
1756
  padding: { top: 0, bottom: 0, left: 1, right: 1 },
1818
1757
  borderColor: 'cyan',
1819
1758
  borderStyle: 'round',
1820
1759
  }));
1821
- const inputCode = await safeInput({ message: '席位卡密' });
1760
+ const inputCode = await safeInput({ message: '请输入卡密' });
1822
1761
  if (!inputCode) {
1823
- return; // 直接返回主菜单
1762
+ return;
1824
1763
  }
1825
- process.stdout.write(chalk.cyan('\n正在连接席位网关验证卡密有效性... '));
1764
+ process.stdout.write(chalk.cyan('\n正在验证卡密... '));
1826
1765
  const testRes = await refundService.getClient().login(inputCode);
1827
1766
  if (!testRes.success || !testRes.data) {
1828
- console.log(chalk.red('✖ 失败\n'));
1767
+ console.log(chalk.red('✖ 不可用\n'));
1768
+ const { humanHint } = ExtractService.summarizeCardError(testRes.error);
1829
1769
  console.log(boxen([
1830
1770
  chalk.bold.red('✖ 卡密验证未通过'),
1831
1771
  chalk.dim('────────────────────────────────────────────────'),
1832
- ` 错误反馈 : ${chalk.yellow(testRes.error || '无效卡密或网络不可达')}`,
1833
- ' 排查建议 : 请检查卡密拼写,确保无多余前后空格。',
1772
+ ` 原因 : ${chalk.yellow(humanHint)}`,
1834
1773
  ].join('\n'), {
1835
1774
  padding: { top: 0, bottom: 0, left: 1, right: 1 },
1836
1775
  borderColor: 'red',
@@ -1839,91 +1778,99 @@ async function handleRefundMenu(store, currentAcc) {
1839
1778
  await pressAnyKey();
1840
1779
  return;
1841
1780
  }
1842
- console.log(chalk.green('✔ 验证通过!卡密已成功保存在本地配置,后续无需重复输入。\n'));
1781
+ console.log(chalk.green('✔ 验证通过!\n'));
1843
1782
  config.setSeatCardCode(inputCode);
1844
1783
  cardCode = inputCode;
1845
1784
  cachedAuthInfo = testRes.data;
1785
+ lastAuthError = '';
1846
1786
  lastVerifiedCard = inputCode;
1847
1787
  await new Promise((r) => setTimeout(r, 800));
1848
1788
  }
1849
- // 2. 已有卡密状态下的极简控制面板 (扁平直达,核心操作一目了然)
1850
1789
  while (true) {
1851
- console.clear();
1852
- // 缓存鉴权状态,避免每次切菜单都发网络请求
1853
1790
  if (cardCode && cardCode !== lastVerifiedCard) {
1854
1791
  try {
1855
1792
  const loginRes = await refundService.getClient().login(cardCode);
1856
1793
  if (loginRes.success && loginRes.data) {
1857
1794
  cachedAuthInfo = loginRes.data;
1795
+ lastAuthError = '';
1858
1796
  lastVerifiedCard = cardCode;
1859
1797
  }
1860
1798
  else {
1861
1799
  cachedAuthInfo = null;
1800
+ lastAuthError = loginRes.error || '卡密无效或已停用';
1801
+ lastVerifiedCard = cardCode;
1862
1802
  }
1863
1803
  }
1864
1804
  catch {
1865
1805
  cachedAuthInfo = null;
1806
+ lastAuthError = '网络异常,请重试';
1866
1807
  }
1867
1808
  }
1809
+ const refundErr = !cachedAuthInfo && lastAuthError ? ExtractService.summarizeCardError(lastAuthError) : null;
1868
1810
  const cardInfoDesc = cardCode
1869
1811
  ? cachedAuthInfo
1870
- ? `${chalk.white(maskToken(cardCode))} ${chalk.dim('[本地已记忆]')} | 剩余: ${chalk.bold.green(cachedAuthInfo.remaining)} 点 | 费率: ${cachedAuthInfo.pointsPerOp} 点/单`
1871
- : `${chalk.white(maskToken(cardCode))} ${chalk.dim('[本地已记忆]')}`
1872
- : chalk.yellow('○ 尚未绑定席位卡密');
1873
- const currentEmailStr = currentAcc?.email ? chalk.bold.white(currentAcc.email) : chalk.dim('未检测到激活中的账号');
1812
+ ? `${chalk.white(maskToken(cardCode))} | 剩余: ${chalk.bold.green(cachedAuthInfo.remaining)} 点 (${cachedAuthInfo.pointsPerOp} 点/次)`
1813
+ : refundErr
1814
+ ? `${chalk.white(maskToken(cardCode))} | ${chalk.bold.red(`${refundErr.shortTag} (按 3 换卡)`)}`
1815
+ : `${chalk.white(maskToken(cardCode))} ${chalk.dim('[本地已存]')}`
1816
+ : chalk.yellow('未绑定卡密');
1817
+ const currentEmailStr = currentAcc?.email ? chalk.bold.white(currentAcc.email) : chalk.dim('未登录');
1874
1818
  const subHeader = boxen([
1875
- `${chalk.bold.cyan('CURSOR-SWITCH')} ${chalk.dim('●')} ${chalk.bold.white('奥仔席位退款服务')} ${chalk.dim('●')} ${chalk.green('官方团队通道 · 失败全额秒退')}`,
1876
- chalk.dim('──────────────────────────────────────────────────────────────────'),
1877
- ` 席位卡密 : ${cardInfoDesc}`,
1878
- ` 当前账号 : ${currentEmailStr}`,
1819
+ `${chalk.bold.cyan('CURSOR-SWITCH')} ${chalk.dim('●')} ${chalk.bold.white('Cursor 退款')} ${chalk.green('失败退点')}`,
1820
+ chalk.dim('────────────────────────────────────────────────────────'),
1821
+ ` 卡密 : ${cardInfoDesc}`,
1822
+ ...(refundErr ? [` 提示 : ${chalk.yellow(refundErr.humanHint)}`] : []),
1823
+ ` 账号 : ${currentEmailStr}`,
1879
1824
  ].join('\n'), {
1880
1825
  padding: { top: 0, bottom: 0, left: 1, right: 1 },
1881
1826
  margin: { top: 0, bottom: 0, left: 0, right: 0 },
1882
- borderColor: 'gray',
1827
+ borderColor: refundErr ? 'yellow' : 'gray',
1883
1828
  borderStyle: 'round',
1884
1829
  });
1885
1830
  const targetDesc = currentAcc?.email
1886
- ? `为当前电脑正在使用的账号 (${currentAcc.email}) 执行退款(恢复为 Free)`
1887
- : '为当前登录账号执行席位退款(恢复为 Free)';
1831
+ ? `退款 ${currentAcc.email} 并恢复 Free`
1832
+ : '退款当前账号并恢复 Free';
1888
1833
  const choices = [
1889
1834
  {
1890
- name: `1. 立即为当前账号退款 ${currentAcc?.email ? chalk.dim(`(${currentAcc.email})`) : ''}`.trim(),
1835
+ name: `1. 退款当前账号 ${currentAcc?.email ? chalk.dim(`(${currentAcc.email})`) : ''}`.trim(),
1891
1836
  value: 'current',
1892
1837
  description: targetDesc,
1893
1838
  },
1894
1839
  {
1895
- name: '2. 选择其他账号退款...',
1840
+ name: '2. 选择其他账号 / 粘贴 Token',
1896
1841
  value: 'select',
1897
- description: '从本地已保存账号库中挑选,或手动粘贴会话凭据 Token 执行退款',
1842
+ description: '从列表选号或粘贴 Token 退款',
1898
1843
  },
1899
1844
  {
1900
- name: `3. 更换席位卡密 ${cachedAuthInfo ? chalk.dim(`(当前剩余: ${cachedAuthInfo.remaining} 点)`) : ''}`.trim(),
1845
+ name: `3. 更换卡密 ${cachedAuthInfo ? chalk.dim(`(剩 ${cachedAuthInfo.remaining} 点)`) : ''}`.trim(),
1901
1846
  value: 'rebind',
1902
- description: '绑定新的奥仔席位卡密(自动更新本地配置)',
1847
+ description: '更换退款卡密',
1903
1848
  },
1904
1849
  {
1905
- name: '4. 查看卡密流水明细',
1850
+ name: '4. 使用记录',
1906
1851
  value: 'usage',
1907
- description: '查询历史加入时间、目标账号、扣点与退款记录',
1852
+ description: '查询退款与扣点记录',
1908
1853
  },
1909
1854
  new Separator(),
1910
1855
  {
1911
- name: '0. 返回主菜单',
1856
+ name: '0. 返回',
1912
1857
  value: '__back__',
1913
- description: '退出奥仔退款面板返回上一级',
1858
+ description: '返回主菜单',
1914
1859
  },
1915
1860
  ];
1916
1861
  let action;
1917
1862
  try {
1918
1863
  action = await quickSelect({
1919
1864
  header: subHeader,
1920
- message: '操作选择 (按键快捷直达):',
1865
+ message: '选择操作:',
1921
1866
  choices,
1922
1867
  pageSize: 7,
1868
+ altScreen: true,
1923
1869
  });
1924
1870
  }
1925
1871
  catch (err) {
1926
1872
  if (err?.name === 'ExitPromptError') {
1873
+ leaveAltScreenIfActive();
1927
1874
  process.stdout.write('\x1b[?25h\n');
1928
1875
  process.exit(0);
1929
1876
  }
@@ -1932,7 +1879,6 @@ async function handleRefundMenu(store, currentAcc) {
1932
1879
  if (action === '__back__' || action === 'exit') {
1933
1880
  return;
1934
1881
  }
1935
- // 1. 退款当前账号
1936
1882
  if (action === 'current') {
1937
1883
  if (!currentAcc) {
1938
1884
  console.clear();
@@ -1954,9 +1900,7 @@ async function handleRefundMenu(store, currentAcc) {
1954
1900
  });
1955
1901
  continue;
1956
1902
  }
1957
- // 2. 选择其他账号退款 (支持本地列表 + 手动粘贴 Token)
1958
1903
  if (action === 'select') {
1959
- console.clear();
1960
1904
  const accounts = store.loadAll();
1961
1905
  const accChoices = [
1962
1906
  {
@@ -1983,10 +1927,12 @@ async function handleRefundMenu(store, currentAcc) {
1983
1927
  message: '请选择目标账号或方式 (按键快捷直达):',
1984
1928
  choices: accChoices,
1985
1929
  pageSize: 12,
1930
+ altScreen: true,
1986
1931
  });
1987
1932
  }
1988
1933
  catch (err) {
1989
1934
  if (err?.name === 'ExitPromptError') {
1935
+ leaveAltScreenIfActive();
1990
1936
  process.stdout.write('\x1b[?25h\n');
1991
1937
  process.exit(0);
1992
1938
  }
@@ -2030,14 +1976,13 @@ async function handleRefundMenu(store, currentAcc) {
2030
1976
  }
2031
1977
  continue;
2032
1978
  }
2033
- // 3. 更换席位卡密 (直接从主菜单进入,扁平快捷)
2034
1979
  if (action === 'rebind') {
2035
1980
  console.clear();
2036
1981
  console.log(boxen([
2037
- chalk.bold.cyan('● 更换席位卡密'),
1982
+ chalk.bold.cyan('● 更换退款卡密'),
2038
1983
  chalk.dim('────────────────────────────────────────────────'),
2039
1984
  ` 当前卡密 : ${cardCode ? chalk.white(maskToken(cardCode)) : chalk.dim('无')} (剩余: ${cachedAuthInfo?.remaining ?? '--'} 点)`,
2040
- ' 请输入新的奥仔席位卡密 (验证通过后自动更新本地配置)。',
1985
+ ' 请输入新的 Cursor 退款服务卡密 (验证通过后自动更新本地配置)。',
2041
1986
  chalk.dim('• 本地安全 : 仅保存于本地 ~/.cursor-switch/config.json'),
2042
1987
  chalk.dim('• 取消方式 : 输入 0、q 或直接按回车可取消返回'),
2043
1988
  ].join('\n'), {
@@ -2045,25 +1990,24 @@ async function handleRefundMenu(store, currentAcc) {
2045
1990
  borderColor: 'cyan',
2046
1991
  borderStyle: 'round',
2047
1992
  }));
2048
- const newCode = await safeInput({ message: '新席位卡密' });
1993
+ const newCode = await safeInput({ message: '新退款卡密' });
2049
1994
  if (!newCode || newCode === '0' || newCode.toLowerCase() === 'q') {
2050
1995
  continue;
2051
1996
  }
2052
- process.stdout.write(chalk.cyan('\n正在连接席位网关验证卡密有效性... '));
1997
+ process.stdout.write(chalk.cyan('\n正在连接 Cursor 退款服务网关验证卡密有效性... '));
2053
1998
  const testRes = await refundService.getClient().login(newCode);
2054
1999
  if (testRes.success && testRes.data) {
2055
2000
  console.log(chalk.green('✔ 验证通过\n'));
2056
2001
  config.setSeatCardCode(newCode);
2057
2002
  cardCode = newCode;
2058
2003
  cachedAuthInfo = testRes.data;
2004
+ lastAuthError = '';
2059
2005
  lastVerifiedCard = newCode;
2060
2006
  console.log(boxen([
2061
- chalk.bold.green('✔ 席位卡密已更新成功!'),
2007
+ chalk.bold.green('✔ 退款卡密已更新!'),
2062
2008
  chalk.dim('────────────────────────────────────────────────'),
2063
- ` 新卡密凭据 : ${chalk.white(maskToken(newCode))}`,
2064
- ` 点数余量 : ${chalk.bold.green(testRes.data.remaining)} 点`,
2065
- ` 单次费率 : ${chalk.yellow(testRes.data.pointsPerOp)} 点/单`,
2066
- chalk.dim(' 已永久更新至本地配置,后续打开无需再次输入。'),
2009
+ ` 新卡密 : ${chalk.white(maskToken(newCode))}`,
2010
+ ` 剩余 : ${chalk.bold.green(testRes.data.remaining)} 点 (${testRes.data.pointsPerOp} 点/次)`,
2067
2011
  ].join('\n'), {
2068
2012
  padding: { top: 0, bottom: 0, left: 1, right: 1 },
2069
2013
  borderColor: 'green',
@@ -2071,12 +2015,13 @@ async function handleRefundMenu(store, currentAcc) {
2071
2015
  }));
2072
2016
  }
2073
2017
  else {
2074
- console.log(chalk.red('✖ 失败\n'));
2018
+ console.log(chalk.red('✖ 不可用\n'));
2019
+ const { humanHint } = ExtractService.summarizeCardError(testRes.error);
2075
2020
  console.log(boxen([
2076
2021
  chalk.bold.red('✖ 卡密验证未通过'),
2077
2022
  chalk.dim('────────────────────────────────────────────────'),
2078
- ` 错误反馈 : ${chalk.yellow(testRes.error || '无效卡密或网络不可达')}`,
2079
- ' 未作任何更改,原卡密仍然保持生效。',
2023
+ ` 原因 : ${chalk.yellow(humanHint)}`,
2024
+ ' 说明 : 未作更改,仍保留原卡密。',
2080
2025
  ].join('\n'), {
2081
2026
  padding: { top: 0, bottom: 0, left: 1, right: 1 },
2082
2027
  borderColor: 'red',
@@ -2086,16 +2031,12 @@ async function handleRefundMenu(store, currentAcc) {
2086
2031
  await pressAnyKey();
2087
2032
  continue;
2088
2033
  }
2089
- // 4. 查看卡密流水明细 (直接从主菜单进入)
2090
2034
  if (action === 'usage') {
2091
2035
  await refundService.printUsageHistory(cardCode || undefined);
2092
2036
  continue;
2093
2037
  }
2094
2038
  }
2095
2039
  }
2096
- /**
2097
- * 版本检查与一键自升级交互子流程
2098
- */
2099
2040
  async function handleUpgradeMenu(updateChecker) {
2100
2041
  console.clear();
2101
2042
  console.log(chalk.bold.cyan('\n● 检查更新 / 在线升级 (Online Version Checker & Upgrader)\n'));
@@ -2125,12 +2066,12 @@ async function handleUpgradeMenu(updateChecker) {
2125
2066
  let choice;
2126
2067
  try {
2127
2068
  choice = await quickSelect({
2128
- message: '请选择升级方式:',
2069
+ message: '升级方式:',
2129
2070
  choices: [
2130
- { name: '1. 立即升级 (官方 npm 源)', value: 'npm', description: `使用 ${pm.name} 从官方源执行全局升级` },
2131
- { name: '2. 极速升级 (国内 npmmirror 镜像源)', value: 'mirror', description: '适用于国内网络,下载速度更快更稳定' },
2071
+ { name: '1. npm 官方源升级', value: 'npm', description: `使用 ${pm.name} 从官方源升级` },
2072
+ { name: '2. 国内镜像升级 (npmmirror)', value: 'mirror', description: '使用国内镜像下载升级' },
2132
2073
  new Separator(),
2133
- { name: '0. 暂不升级,返回主菜单', value: '__back__' },
2074
+ { name: '0. 返回', value: '__back__' },
2134
2075
  ],
2135
2076
  });
2136
2077
  }
@@ -2162,40 +2103,6 @@ async function handleUpgradeMenu(updateChecker) {
2162
2103
  }
2163
2104
  await pressAnyKey();
2164
2105
  }
2165
- /**
2166
- * 调起默认浏览器打开 AI 折腾局官网
2167
- */
2168
- async function handleOpenWebsiteAction() {
2169
- const url = 'https://getdoubao.com';
2170
- console.log(chalk.cyan(`\n正在调起系统默认浏览器打开 AI 折腾局官网: ${chalk.bold.white(url)} ...`));
2171
- const ok = await openBrowserUrl(url);
2172
- if (ok) {
2173
- console.log(chalk.green('✔ 官网已在默认浏览器中打开 (含折腾手册、开源工具、福利与自助服务)\n'));
2174
- }
2175
- else {
2176
- console.log(chalk.yellow(`未能自动唤起浏览器,请手动复制并在浏览器中打开: ${url}\n`));
2177
- }
2178
- await pressAnyKey();
2179
- }
2180
- /**
2181
- * 官方 QQ 交流群展示与一键复制
2182
- */
2183
- async function handleQqGroupAction() {
2184
- const qqGroup = '1007446249';
2185
- const copied = await copyToClipboard(qqGroup);
2186
- console.clear();
2187
- console.log(chalk.bold.cyan('\n● 官方 QQ 交流群 (Community & Support)\n'));
2188
- console.log(boxen([
2189
- `${chalk.bold.yellow('🐧 欢迎加入 AI 折腾局官方交流群')}`,
2190
- chalk.dim('────────────────────────────────────────────────'),
2191
- ` QQ 群号 : ${chalk.bold.green(qqGroup)}`,
2192
- ` 群号复制 : ${copied ? chalk.green('✔ 已自动复制到系统剪贴板 (直接在 QQ 粘贴即可查找加入)') : chalk.yellow('○ 请手动选中群号复制')}`,
2193
- ` 官方网站 : ${chalk.cyan('https://getdoubao.com')}`,
2194
- ` 交流内容 : ${chalk.white('Cursor 技巧分享 · 账号与防封交流 · 脚本升级答疑 · 售后支持')}`,
2195
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'cyan', borderStyle: 'round' }));
2196
- console.log(chalk.grey('\n操作提示: 打开 QQ 客户端 -> 点击「添加群聊」-> 粘贴群号即可快速申请加入。\n'));
2197
- await pressAnyKey();
2198
- }
2199
2106
  async function pressAnyKey() {
2200
2107
  await safePressAnyKey('按回车或 Esc 键返回...');
2201
2108
  }