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
@@ -1,36 +1,44 @@
1
- /**
2
- * Cursor 动态纯净住宅 IP 自动代登与 Token 提取服务
3
- * 直连海外 S 级原生家宽代理集群与 Rust Worker 算力节点
4
- * 支持智能解构多段式格式、Turnstile 极速解盾、收件箱自动取码、Token 秒提与换号无缝联动
5
- */
6
1
  import chalk from 'chalk';
7
2
  import boxen from 'boxen';
8
3
  import { ConfigStore } from './config-store.js';
9
4
  import { ProcessManager } from './process-manager.js';
10
5
  import { OfficialApiClient } from './official-api.js';
11
6
  import { TokenParser } from './token-parser.js';
12
- import { generateMachineIds, formatMachineIdSummary } from './fingerprint.js';
13
- import { formatPlanBadge } from '../utils/plan-formatter.js';
7
+ import { executeAccountSwitch } from './switch-orchestrator.js';
8
+ import { formatMachineIdSummary, generateMachineIds } from './fingerprint.js';
14
9
  import { safeInput, safeConfirm, safePressAnyKey } from '../utils/prompt-utils.js';
15
10
  import { OutlookLauncher } from './outlook-launcher.js';
16
- import { copyToClipboard } from '../utils/clipboard.js';
11
+ import { ensureGlobalProxy, formatNetworkError } from '../utils/proxy-bootstrap.js';
12
+ import { printExtractedCredentialsResult } from '../utils/credential-bundle-ui.js';
17
13
  export class PureLoginService {
18
14
  configStore;
19
- constructor() {
15
+ customApiBase;
16
+ constructor(customApiBase) {
17
+ ensureGlobalProxy();
20
18
  this.configStore = new ConfigStore();
19
+ if (customApiBase) {
20
+ this.customApiBase = customApiBase.replace(/\/+$/, '');
21
+ }
21
22
  }
22
- /**
23
- * 智能解析账号输入串 (支持 ----, ---, --, |, \t, 双空格, 逗号 等各类分隔符)
24
- * 严格遵循规则:两段式第二段 100% 映射为邮箱密码用于自动收信取码
25
- */
26
- parseAccountString(raw) {
23
+ getApiBase() {
24
+ return (this.customApiBase || this.configStore.getSeatApiBase()).replace(/\/+$/, '');
25
+ }
26
+ getConfigStore() {
27
+ return this.configStore;
28
+ }
29
+ splitAccountParts(raw) {
27
30
  if (!raw)
28
- return { email: '', emailPassword: '', cursorPassword: '' };
31
+ return [];
29
32
  const text = raw.trim();
33
+ const ambiguousSingleDelims = new Set(['--', '|', ',']);
30
34
  let parts = [];
31
35
  for (const delim of ['----', '---', '--', '|', '\t', ' ', ',']) {
32
36
  if (text.includes(delim)) {
33
- parts = text.split(delim).map((s) => s.trim()).filter(Boolean);
37
+ const candidate = text.split(delim).map((s) => s.trim()).filter(Boolean);
38
+ if (ambiguousSingleDelims.has(delim) && /\s/.test(candidate[0] || '')) {
39
+ continue;
40
+ }
41
+ parts = candidate;
34
42
  break;
35
43
  }
36
44
  }
@@ -42,6 +50,19 @@ export class PureLoginService {
42
50
  parts = [text];
43
51
  }
44
52
  }
53
+ return parts;
54
+ }
55
+ parseEmailCredentials(raw) {
56
+ const parts = this.splitAccountParts(raw);
57
+ const email = (parts[0] || '').trim();
58
+ let emailPassword = (parts[1] || '').trim();
59
+ if (parts.length === 2 && /\s+\/\//.test(emailPassword)) {
60
+ emailPassword = emailPassword.replace(/\s+\/\/.*$/, '').trim();
61
+ }
62
+ return { email, emailPassword };
63
+ }
64
+ parseAccountString(raw) {
65
+ const parts = this.splitAccountParts(raw);
45
66
  let email = '';
46
67
  let emailPassword = '';
47
68
  let cursorPassword = '';
@@ -62,18 +83,16 @@ export class PureLoginService {
62
83
  }
63
84
  return { email, emailPassword, cursorPassword };
64
85
  }
65
- /**
66
- * 校验卡密有效性与剩余可用次数
67
- */
68
86
  async checkKey(code) {
69
- const apiBase = this.configStore.getSeatApiBase();
87
+ const apiBase = this.getApiBase();
70
88
  try {
71
89
  const res = await fetch(`${apiBase}/api/v1/token-service/check-key`, {
72
90
  method: 'POST',
73
91
  headers: { 'Content-Type': 'application/json' },
74
92
  body: JSON.stringify({ code: code.trim() }),
93
+ signal: AbortSignal.timeout(15000),
75
94
  });
76
- const data = await res.json();
95
+ const data = await res.json().catch(() => ({}));
77
96
  if (res.ok && data.valid) {
78
97
  return {
79
98
  valid: true,
@@ -84,33 +103,35 @@ export class PureLoginService {
84
103
  }
85
104
  return {
86
105
  valid: false,
87
- detail: data.detail || '卡密无效或已用尽',
106
+ detail: data.detail || `卡密无效或已用尽 (HTTP ${res.status})`,
88
107
  };
89
108
  }
90
109
  catch (err) {
91
110
  return {
92
111
  valid: false,
93
- detail: `网络连接异常: ${err.message}`,
112
+ detail: `网络连接异常: ${formatNetworkError(err)}`,
94
113
  };
95
114
  }
96
115
  }
97
- /**
98
- * 启动纯净代登任务
99
- */
100
116
  async startTask(params) {
101
- const apiBase = this.configStore.getSeatApiBase();
117
+ const apiBase = this.getApiBase();
102
118
  try {
119
+ const payload = {
120
+ code: params.code.trim(),
121
+ email: params.email.trim(),
122
+ mode: 'browser',
123
+ };
124
+ if (params.emailPassword?.trim()) {
125
+ payload.email_password = params.emailPassword.trim();
126
+ }
127
+ if (params.cursorPassword?.trim()) {
128
+ payload.cursor_password = params.cursorPassword.trim();
129
+ }
103
130
  const res = await fetch(`${apiBase}/api/v1/token-service/start`, {
104
131
  method: 'POST',
105
132
  headers: { 'Content-Type': 'application/json' },
106
- body: JSON.stringify({
107
- code: params.code.trim(),
108
- email: params.email.trim(),
109
- email_password: params.emailPassword?.trim() || '',
110
- cursor_password: params.cursorPassword?.trim() || '',
111
- raw_account: params.rawAccount?.trim() || '',
112
- mode: 'browser',
113
- }),
133
+ body: JSON.stringify(payload),
134
+ signal: AbortSignal.timeout(20000),
114
135
  });
115
136
  const data = await res.json();
116
137
  if (res.ok && (data.ok || data.task_id)) {
@@ -129,15 +150,12 @@ export class PureLoginService {
129
150
  catch (err) {
130
151
  return {
131
152
  ok: false,
132
- detail: `请求超时或连接失败: ${err.message}`,
153
+ detail: `请求超时或连接失败: ${formatNetworkError(err)}`,
133
154
  };
134
155
  }
135
156
  }
136
- /**
137
- * 提交 6 位邮箱验证码或短信验证码
138
- */
139
157
  async submitOtp(taskId, cardCode, otpCode) {
140
- const apiBase = this.configStore.getSeatApiBase();
158
+ const apiBase = this.getApiBase();
141
159
  try {
142
160
  const res = await fetch(`${apiBase}/api/v1/token-service/submit-code`, {
143
161
  method: 'POST',
@@ -147,12 +165,15 @@ export class PureLoginService {
147
165
  card_code: cardCode.trim(),
148
166
  otp_code: otpCode.trim(),
149
167
  }),
168
+ signal: AbortSignal.timeout(20000),
150
169
  });
151
170
  const data = await res.json();
152
171
  if (res.ok && (data.ok || data.success)) {
153
172
  return {
154
173
  ok: true,
155
174
  token: data.token || data.cursor_token,
175
+ accessToken: data.access_token || data.accessToken,
176
+ refreshToken: data.refresh_token || data.refreshToken,
156
177
  email: data.email,
157
178
  detail: data.detail || data.msg,
158
179
  };
@@ -176,50 +197,242 @@ export class PureLoginService {
176
197
  return {
177
198
  ok: false,
178
199
  canRetry: true,
179
- detail: `网络连接异常: ${err.message}`,
200
+ detail: `网络连接异常: ${formatNetworkError(err)}`,
180
201
  };
181
202
  }
182
203
  }
183
- /**
184
- * 自动从用户邮箱中提取最新 6 位数字验证码 (多轮自动拉取)
185
- */
186
- async autoFetchMailCode(email, emailPassword, cursorPassword) {
187
- const apiBase = this.configStore.getSeatApiBase();
204
+ async resendCode(taskId, cardCode, email) {
205
+ const apiBase = this.getApiBase();
188
206
  try {
189
- const res = await fetch(`${apiBase}/api/v1/mail/code`, {
207
+ const res = await fetch(`${apiBase}/api/v1/token-service/resend-code`, {
190
208
  method: 'POST',
191
209
  headers: { 'Content-Type': 'application/json' },
192
210
  body: JSON.stringify({
193
- account: email.trim(),
194
- emailPassword: emailPassword.trim(),
195
- cursorPassword: cursorPassword?.trim() || '',
211
+ task_id: taskId,
212
+ card_code: cardCode.trim(),
213
+ email: email.trim(),
196
214
  }),
215
+ signal: AbortSignal.timeout(15000),
197
216
  });
198
- const data = await res.json();
199
- if (res.ok) {
200
- if (data.code && /^\d{6}$/.test(data.code)) {
201
- return data.code;
217
+ const data = await res.json().catch(() => ({}));
218
+ if (res.ok && data.success) {
219
+ return { ok: true, message: data.message || '已重新向 Cursor 鉴权中心请求发送最新验证码!' };
220
+ }
221
+ return { ok: false, message: data.detail || data.error || '重新请求发信失败,请稍后重试' };
222
+ }
223
+ catch (err) {
224
+ return { ok: false, message: `网络连接异常: ${formatNetworkError(err)}` };
225
+ }
226
+ }
227
+ async cancelTask(taskId, cardCode) {
228
+ const apiBase = this.getApiBase();
229
+ try {
230
+ await fetch(`${apiBase}/api/v1/token-service/cancel`, {
231
+ method: 'POST',
232
+ headers: { 'Content-Type': 'application/json' },
233
+ body: JSON.stringify({
234
+ task_id: taskId,
235
+ card_code: cardCode.trim(),
236
+ }),
237
+ signal: AbortSignal.timeout(4000),
238
+ });
239
+ }
240
+ catch { }
241
+ }
242
+ async saveExtractedAccount(store, params) {
243
+ const parsedToken = TokenParser.parse(params.token);
244
+ const usageRes = await OfficialApiClient.fetchUsage(parsedToken.token);
245
+ const finalToken = (params.accessToken && TokenParser.isJwtShaped(params.accessToken.trim())
246
+ ? params.accessToken.trim()
247
+ : undefined) || parsedToken.token;
248
+ const finalRefreshToken = (params.refreshToken && !params.refreshToken.includes('::') ? params.refreshToken.trim() : undefined) ||
249
+ parsedToken.refreshToken;
250
+ const rawWorkosSession = parsedToken.workosSessionToken ||
251
+ (parsedToken.userId ? `${parsedToken.userId}::${parsedToken.token}` : undefined);
252
+ const existing = store.getByEmail(params.email);
253
+ const machineIds = existing?.machine_ids || generateMachineIds();
254
+ const mergedCheckout = existing?.checkout_links || params.checkoutLinks
255
+ ? {
256
+ ...(existing?.checkout_links || {}),
257
+ ...(params.checkoutLinks || {}),
258
+ }
259
+ : undefined;
260
+ const account = {
261
+ email: params.email,
262
+ token: finalToken,
263
+ refresh_token: finalRefreshToken || existing?.refresh_token,
264
+ workos_cursor_session_token: rawWorkosSession,
265
+ subscription_type: usageRes.success && usageRes.subscriptionType ? usageRes.subscriptionType : existing?.subscription_type || 'free',
266
+ current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
267
+ machine_ids: machineIds,
268
+ email_password: params.emailPassword || existing?.email_password,
269
+ cursor_password: params.cursorPassword || existing?.cursor_password,
270
+ checkout_links: mergedCheckout,
271
+ };
272
+ store.addOrUpdate(account);
273
+ return { account, machineIds };
274
+ }
275
+ async streamTaskEvents(params) {
276
+ const apiBase = this.getApiBase();
277
+ const tokenQuery = params.taskToken ? `?token=${encodeURIComponent(params.taskToken)}` : '';
278
+ const abortController = new AbortController();
279
+ let terminalResult = null;
280
+ let pendingHandler = null;
281
+ let handledNeedCode = false;
282
+ const finishWith = (res) => {
283
+ if (!terminalResult) {
284
+ terminalResult = res;
285
+ abortController.abort();
286
+ }
287
+ };
288
+ try {
289
+ const sseRes = await fetch(`${apiBase}/api/v1/token-service/events/${params.taskId}${tokenQuery}`, {
290
+ headers: { Accept: 'text/event-stream' },
291
+ signal: abortController.signal,
292
+ });
293
+ if (!sseRes.ok || !sseRes.body) {
294
+ return { ok: false, error: `SSE 状态连接异常 (HTTP ${sseRes.status})` };
295
+ }
296
+ const reader = sseRes.body.getReader();
297
+ const decoder = new TextDecoder();
298
+ let buffer = '';
299
+ let currentEvent = 'message';
300
+ while (!terminalResult) {
301
+ let done = false;
302
+ let value;
303
+ try {
304
+ ({ done, value } = await reader.read());
305
+ }
306
+ catch (err) {
307
+ if (abortController.signal.aborted || terminalResult)
308
+ break;
309
+ throw err;
202
310
  }
203
- if (Array.isArray(data.mails)) {
204
- for (const m of data.mails) {
205
- const text = `${m.subject || ''} ${m.body || m.content || ''}`;
206
- const match = text.match(/\b\d{6}\b/);
207
- if (match)
208
- return match[0];
311
+ if (done)
312
+ break;
313
+ buffer += decoder.decode(value, { stream: true });
314
+ const lines = buffer.split(/\r?\n/);
315
+ buffer = lines.pop() || '';
316
+ for (const line of lines) {
317
+ if (terminalResult)
318
+ break;
319
+ if (line.trim() === '') {
320
+ currentEvent = 'message';
321
+ continue;
322
+ }
323
+ if (line.startsWith('event:')) {
324
+ currentEvent = line.replace(/^event:\s*/, '').trim();
325
+ }
326
+ else if (line.startsWith('data:')) {
327
+ const dataStr = line.replace(/^data:\s*/, '').trim();
328
+ const eventName = currentEvent;
329
+ currentEvent = 'message';
330
+ if (!dataStr)
331
+ continue;
332
+ try {
333
+ const data = JSON.parse(dataStr);
334
+ if (data.token) {
335
+ finishWith({ ok: true, token: data.token, email: data.email });
336
+ break;
337
+ }
338
+ if (eventName === 'status') {
339
+ params.onStatus?.(data.step || '', data.msg || '正在推进登录鉴权...');
340
+ }
341
+ else if (eventName === 'need_code' && !handledNeedCode) {
342
+ handledNeedCode = true;
343
+ pendingHandler = params
344
+ .onNeedCode(data, abortController.signal)
345
+ .then((outcome) => {
346
+ if (outcome.action === 'token') {
347
+ finishWith({
348
+ ok: true,
349
+ token: outcome.token,
350
+ accessToken: outcome.accessToken,
351
+ refreshToken: outcome.refreshToken,
352
+ email: outcome.email,
353
+ });
354
+ }
355
+ else if (outcome.action === 'abort') {
356
+ finishWith({ ok: false, error: outcome.error || '代登验证码阶段中止' });
357
+ }
358
+ })
359
+ .catch((e) => {
360
+ finishWith({ ok: false, error: e?.message || '验证码处理异常' });
361
+ });
362
+ }
363
+ else if (eventName === 'need_sms_code') {
364
+ if (params.onNeedSmsCode) {
365
+ pendingHandler = params
366
+ .onNeedSmsCode(data, abortController.signal)
367
+ .then((outcome) => {
368
+ if (outcome.action === 'token') {
369
+ finishWith({
370
+ ok: true,
371
+ token: outcome.token,
372
+ accessToken: outcome.accessToken,
373
+ refreshToken: outcome.refreshToken,
374
+ email: outcome.email,
375
+ });
376
+ }
377
+ else if (outcome.action === 'abort') {
378
+ finishWith({ ok: false, error: outcome.error || '手机短信验证未完成', isPhoneChallenge: true });
379
+ }
380
+ })
381
+ .catch((e) => {
382
+ finishWith({ ok: false, error: e?.message || '短信验证处理异常', isPhoneChallenge: true });
383
+ });
384
+ }
385
+ else {
386
+ finishWith({
387
+ ok: false,
388
+ isPhoneChallenge: true,
389
+ error: `检测到手机二次短信验证 (${data.phoneMask || '••••'}),无法自动完成`,
390
+ });
391
+ break;
392
+ }
393
+ }
394
+ else if (eventName === 'success') {
395
+ finishWith({
396
+ ok: true,
397
+ token: data.token,
398
+ accessToken: data.access_token || data.accessToken,
399
+ refreshToken: data.refresh_token || data.refreshToken,
400
+ email: data.email,
401
+ });
402
+ break;
403
+ }
404
+ else if (eventName === 'failed' || (data.error && eventName !== 'status')) {
405
+ finishWith({
406
+ ok: false,
407
+ error: data.error || data.detail || '官方服务响应超时或验证失败',
408
+ isPhoneChallenge: Boolean(data.isPhoneChallenge),
409
+ remaining: data.remaining,
410
+ });
411
+ break;
412
+ }
413
+ }
414
+ catch { }
209
415
  }
210
416
  }
211
417
  }
418
+ if (!terminalResult && pendingHandler) {
419
+ await pendingHandler;
420
+ }
421
+ try {
422
+ await reader.cancel();
423
+ }
424
+ catch { }
212
425
  }
213
- catch { }
214
- return null;
426
+ catch (err) {
427
+ if (!terminalResult && !abortController.signal.aborted) {
428
+ return { ok: false, error: `事件监听断开: ${formatNetworkError(err)}` };
429
+ }
430
+ }
431
+ return terminalResult || { ok: false, error: '云端代登已结束,未捕获到有效 Token' };
215
432
  }
216
- /**
217
- * 交互式运行纯净代登全流程 (终端交互式 TUI)
218
- */
219
- async runInteractiveFlow(store, storage, sqlite, executablePath) {
220
- console.log(chalk.bold.cyan('\n☁ 正在连接海外纯净代登云服务...\n'));
221
- console.log(chalk.grey('说明: 100% 云端集群托管执行,本地无需安装代理,全自动过人机盾/收信取码提取 Token。\n'));
222
- // 1. 获取并核验代登卡密 (自动读取记忆,支持一键复用或更换)
433
+ async runInteractiveFlow(store, storage, sqlite, executablePath, options = {}) {
434
+ console.log(chalk.bold.cyan('\n☁ 正在连接 Cursor 纯净代登服务...\n'));
435
+ console.log(chalk.grey('说明: 通过独立代理环境辅助登录,录入邮箱验证码获取 Token(若账号自身触发手机短信风控则无法仅凭邮箱登录;启动即扣 1 次额度,失败不退)。\n'));
223
436
  const savedKey = this.configStore.getTokenCardCode() || this.configStore.getSeatCardCode();
224
437
  let activeKey = '';
225
438
  if (savedKey) {
@@ -242,7 +455,7 @@ export class PureLoginService {
242
455
  message: '请输入【纯净代登卡密】(按 Esc 或输入空返回):',
243
456
  });
244
457
  if (!inputKey)
245
- return;
458
+ return null;
246
459
  const check = await this.checkKey(inputKey);
247
460
  if (check.valid) {
248
461
  activeKey = inputKey.trim();
@@ -254,328 +467,296 @@ export class PureLoginService {
254
467
  console.log(chalk.red(`\n✖ 卡密核验失败: ${check.detail || '无效卡密'}\n`));
255
468
  const retry = await safeConfirm({ message: '是否重新输入卡密?', default: true });
256
469
  if (!retry)
257
- return;
470
+ return null;
258
471
  }
259
472
  }
260
473
  }
261
- // 2. 录入待登账号信息 (支持单邮箱或 邮箱----邮箱密码)
262
- console.log(chalk.grey('提示: 支持单行粘贴,格式如下:') +
263
- '\n' +
264
- chalk.grey(' • 自动取码: ') + chalk.cyan('user@outlook.com----邮箱密码') + chalk.dim(' (推荐,自动登录邮箱提取 6 位验证码,支持 ---- 或 ---)') +
265
- '\n' +
266
- chalk.grey(' • 仅输邮箱: ') + chalk.cyan('user@outlook.com') + chalk.dim(' (云端发码后由您手动在终端输入 6 位验证码)'));
267
- const rawInput = await safeInput({
268
- message: '请输入 Cursor 账号信息:',
269
- });
474
+ let rawInput = options.prefilledInput?.trim();
475
+ if (!rawInput) {
476
+ console.log(chalk.grey('提示: 请输入待登 Cursor 邮箱 (支持直接粘贴 user@outlook.com 或 user@outlook.com----xxx 格式):'));
477
+ rawInput = await safeInput({
478
+ message: '请输入 Cursor 账号信息:',
479
+ });
480
+ }
270
481
  if (!rawInput)
271
- return;
482
+ return null;
272
483
  const parsed = this.parseAccountString(rawInput);
273
484
  if (!parsed.email || !parsed.email.includes('@')) {
274
485
  console.log(chalk.red('\n未识别到有效的邮箱地址,操作已取消。\n'));
275
486
  await safePressAnyKey();
276
- return;
487
+ return null;
277
488
  }
278
- const isAutoMail = Boolean(parsed.emailPassword);
279
489
  console.log(boxen([
280
490
  chalk.bold.white('📋 账号待登要素确认:'),
281
491
  chalk.dim('────────────────────────────────────────────────'),
282
- ` 目标邮箱 : ${chalk.yellow(parsed.email)}`,
283
- ` 邮箱密码 : ${parsed.emailPassword ? chalk.green('● 已提供 (将开启全自动收信取码)') : chalk.dim('○ 未提供 (稍后需手动输入 6 位验证码)')}`,
284
- ` 代登模式 : ${isAutoMail ? chalk.cyan('⚡ 全自动免密极速代登 (无需人工看守)') : chalk.magenta('💬 交互式手动输码代登')}`,
492
+ ` 目标邮箱 : ${chalk.bold.yellow(parsed.email)}`,
493
+ ` 代登模式 : ${chalk.cyan('⚡ 云端代理辅助登录')}`,
494
+ ` 取码方式 : ${chalk.green('💬 查收邮件并在终端输入 6 位验证码')}`,
285
495
  ...(parsed.cursorPassword ? [` 附加信息 : ${chalk.grey('● 已保留备用')}`] : []),
286
496
  ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'blue', borderStyle: 'round' }));
287
- // 3. 启动云端任务并建立 SSE 流式监听
288
- console.log(chalk.cyan('\n正在连接海外住宅集群分配独享出口 IP 并启动任务...'));
497
+ console.log(chalk.cyan('\n正在分配云端代登环境并启动任务...'));
289
498
  const startRes = await this.startTask({
290
499
  code: activeKey,
291
500
  email: parsed.email,
292
501
  emailPassword: parsed.emailPassword,
293
502
  cursorPassword: parsed.cursorPassword,
294
- rawAccount: rawInput,
295
503
  });
296
504
  if (!startRes.ok || !startRes.taskId) {
297
505
  console.log(chalk.red(`\n✖ 任务启动失败: ${startRes.detail || '未知原因'}\n`));
298
506
  await safePressAnyKey();
299
- return;
507
+ return null;
300
508
  }
301
509
  const taskId = startRes.taskId;
302
510
  console.log(chalk.green(`✔ 任务已受理 (TaskID: ${taskId.slice(0, 8)}),正在实时处理...\n`));
303
- // 4. 监听 SSE 事件流
304
- const apiBase = this.configStore.getSeatApiBase();
305
- let finishedToken = null;
306
- let finishedEmail = parsed.email;
307
- try {
308
- const tokenQuery = startRes.taskToken ? `?token=${encodeURIComponent(startRes.taskToken)}` : '';
309
- const sseRes = await fetch(`${apiBase}/api/v1/token-service/events/${taskId}${tokenQuery}`, {
310
- headers: { Accept: 'text/event-stream' },
311
- });
312
- if (!sseRes.ok || !sseRes.body) {
313
- throw new Error(`SSE 状态连接异常 (HTTP ${sseRes.status})`);
314
- }
315
- const reader = sseRes.body.getReader();
316
- const decoder = new TextDecoder();
317
- let buffer = '';
318
- let currentEvent = 'message';
319
- while (true) {
320
- const { done, value } = await reader.read();
321
- if (done)
322
- break;
323
- buffer += decoder.decode(value, { stream: true });
324
- const lines = buffer.split(/\r?\n/);
325
- buffer = lines.pop() || '';
326
- for (const line of lines) {
327
- if (line.startsWith('event:')) {
328
- currentEvent = line.replace(/^event:\s*/, '').trim();
511
+ const streamRes = await this.streamTaskEvents({
512
+ taskId,
513
+ taskToken: startRes.taskToken,
514
+ onStatus: (step, msg) => {
515
+ const prefix = step ? `[${step}] ` : '';
516
+ console.log(chalk.grey(`⏳ ${prefix}${msg}`));
517
+ },
518
+ onNeedCode: async () => {
519
+ console.log(chalk.yellow(`\n📨 Cursor 验证码已派发至您的邮箱 (${parsed.email})`));
520
+ if (parsed.emailPassword) {
521
+ console.log(chalk.cyan('🚀 正在启动本地独立隔离浏览器,自动登录 Outlook 邮箱...'));
522
+ try {
523
+ const mailRes = await OutlookLauncher.openMailbox({
524
+ email: parsed.email,
525
+ emailPassword: parsed.emailPassword,
526
+ sniffOtp: false,
527
+ });
528
+ if (mailRes.status === 'logged_in') {
529
+ console.log(boxen([
530
+ chalk.bold.green('✔ 独立浏览器已自动登入 Outlook 收件箱!'),
531
+ chalk.dim('────────────────────────────────────────────────────────────'),
532
+ chalk.bold.white('💡【取码指引】:'),
533
+ ` 1. 浏览器窗口已置顶展示,请查看最新的 ${chalk.bold.cyan('Cursor')} 官方邮件`,
534
+ ` 2. ${chalk.bold.yellow('特别注意: 若收件箱未看到邮件,请务必点击上方【其他 / Other】分类栏')}`,
535
+ ` 3. 复制或记下邮件中的 6 位数字验证码,直接在下方粘贴/输入`,
536
+ ].join('\n'), {
537
+ padding: { top: 0, bottom: 0, left: 1, right: 1 },
538
+ borderColor: 'green',
539
+ borderStyle: 'round',
540
+ }));
541
+ }
542
+ else if (mailRes.status === 'manual_required') {
543
+ console.log(boxen([
544
+ chalk.bold.yellow('⚠️ 微软要求安全验证 (辅助邮箱 / 二次认证)'),
545
+ chalk.dim('────────────────────────────────────────────────────────────'),
546
+ ` • 浏览器窗口已为您调起并置顶,请在浏览器中完成辅助邮箱验证`,
547
+ ` • 验证成功进入收件箱后,查看最新的 ${chalk.bold.cyan('Cursor')} 验证码并在下方输入`,
548
+ ` • ${chalk.dim('提示: 若收件箱未看到邮件,请查看【其他】分类栏')}`,
549
+ ].join('\n'), {
550
+ padding: { top: 0, bottom: 0, left: 1, right: 1 },
551
+ borderColor: 'yellow',
552
+ borderStyle: 'round',
553
+ }));
554
+ }
555
+ else {
556
+ console.log(chalk.grey(` → 浏览器状态: ${mailRes.message}`));
557
+ }
329
558
  }
330
- else if (line.startsWith('data:')) {
331
- const dataStr = line.replace(/^data:\s*/, '').trim();
332
- if (!dataStr)
333
- continue;
334
- try {
335
- const data = JSON.parse(dataStr);
336
- // 优先检测是否直接携带了 Token
337
- if (data.token) {
338
- finishedToken = data.token;
339
- if (data.email)
340
- finishedEmail = data.email;
341
- break;
342
- }
343
- if (currentEvent === 'status') {
344
- const step = data.step ? `[${data.step}] ` : '';
345
- console.log(chalk.grey(`⏳ ${step}${data.msg || '正在推进登录鉴权...'}`));
346
- }
347
- else if (currentEvent === 'need_code') {
348
- console.log(chalk.yellow(`\n📨 验证码已派发至您的邮箱 (${parsed.email})`));
349
- let otpToSubmit = '';
350
- // 1. 若附带了邮箱密码,优先尝试云端协议 4 轮自动收信
351
- if (parsed.emailPassword) {
352
- console.log(chalk.cyan('正在尝试通过云端协议自动查收 6 位验证码...'));
353
- for (let i = 1; i <= 4; i++) {
354
- await new Promise((r) => setTimeout(r, 2000));
355
- const foundCode = await this.autoFetchMailCode(parsed.email, parsed.emailPassword, parsed.cursorPassword);
356
- if (foundCode) {
357
- otpToSubmit = foundCode;
358
- console.log(chalk.green(`🎉 云端协议自动提取验证码成功: ${chalk.bold.white(foundCode)}`));
359
- break;
360
- }
361
- else {
362
- console.log(chalk.grey(`云端收信重试中 (${i}/4)...`));
363
- }
364
- }
365
- }
366
- // 2. 若云端协议取码未成功且提供了邮箱密码,触发本地独立隔离浏览器登录 Outlook 收件箱取码
367
- if (!otpToSubmit && parsed.emailPassword) {
368
- console.log(chalk.yellow('\n☁ 云端协议收信未就绪 (微软限制或需网页授权)'));
369
- console.log(chalk.cyan('🚀 正在启动本地独立隔离浏览器,自动登录 Outlook 邮箱提取验证码...'));
370
- try {
371
- const mailRes = await OutlookLauncher.openMailbox({
372
- email: parsed.email,
373
- emailPassword: parsed.emailPassword,
374
- sniffOtp: true,
375
- sniffTimeoutMs: 20000,
376
- });
377
- if (mailRes.otpCode) {
378
- otpToSubmit = mailRes.otpCode;
379
- console.log(chalk.green.bold(`\n🎉 本地浏览器已成功捕获验证码: ${chalk.bold.white(otpToSubmit)}`));
380
- }
381
- else if (mailRes.status === 'logged_in') {
382
- console.log(chalk.green('✔ 本地浏览器已成功进入收件箱,请直接查看浏览器中的 6 位数字验证码'));
383
- }
384
- else if (mailRes.status === 'manual_required') {
385
- console.log(chalk.yellow(' → 浏览器已调起,遇辅助邮箱/安全验证请在浏览器中完成'));
386
- }
387
- else {
388
- console.log(chalk.grey(` → 浏览器状态: ${mailRes.message}`));
389
- }
390
- }
391
- catch (e) {
392
- console.log(chalk.yellow(`本地浏览器唤起异常 (${e.message}),转入终端手动输入`));
393
- }
394
- }
395
- // 3. 提交验证码(带严格受控的 3 次重试保护,杜绝无限死循环)
396
- let submitAttempts = 0;
397
- const MAX_ATTEMPTS = 3;
398
- while (submitAttempts < MAX_ATTEMPTS) {
399
- if (!otpToSubmit) {
400
- otpToSubmit = (await safeInput({
401
- message: submitAttempts === 0
402
- ? '请输入收到的 6 位邮箱验证码:'
403
- : `请重新输入 6 位验证码 (剩余 ${MAX_ATTEMPTS - submitAttempts} 次重试机会):`,
404
- })) || '';
405
- }
406
- if (!otpToSubmit) {
407
- console.log(chalk.red('\n未输入验证码,代登已终止。\n'));
408
- await safePressAnyKey();
409
- return;
410
- }
411
- submitAttempts++;
412
- console.log(chalk.cyan('正在提交验证码并生成官方登录凭证...'));
413
- const submitRes = await this.submitOtp(taskId, activeKey, otpToSubmit);
414
- if (submitRes.ok) {
415
- console.log(chalk.green('✔ 验证码已成功提交受理,等待云端签发 Token...'));
416
- if (submitRes.token) {
417
- finishedToken = submitRes.token;
418
- if (submitRes.email)
419
- finishedEmail = submitRes.email;
420
- break;
421
- }
422
- break;
423
- }
424
- else if (submitRes.needsSmsCode) {
425
- console.log(chalk.yellow(`\n📱 检测到手机二次短信验证 (${submitRes.phoneMask || '••••'})`));
426
- const smsCode = (await safeInput({
427
- message: '请输入手机收到的短信验证码:',
428
- })) || '';
429
- if (smsCode) {
430
- console.log(chalk.cyan('正在提交手机验证码...'));
431
- const smsRes = await this.submitOtp(taskId, activeKey, smsCode);
432
- if (smsRes.ok && smsRes.token) {
433
- finishedToken = smsRes.token;
434
- if (smsRes.email)
435
- finishedEmail = smsRes.email;
436
- break;
437
- }
438
- }
439
- break;
440
- }
441
- else if (submitRes.canRetry && submitAttempts < MAX_ATTEMPTS) {
442
- console.log(chalk.yellow(`\n⚠️ 验证码未通过: ${submitRes.detail || '验证码有误或网络抖动'}`));
443
- const shouldRetry = await safeConfirm({
444
- message: `当前代登会话仍有效,是否重新输入验证码?(还可重试 ${MAX_ATTEMPTS - submitAttempts} 次)`,
445
- default: true,
446
- });
447
- if (shouldRetry) {
448
- otpToSubmit = '';
449
- continue;
450
- }
451
- else {
452
- console.log(chalk.grey('\n用户主动取消重试,代登已终止。\n'));
453
- await safePressAnyKey();
454
- return;
455
- }
456
- }
457
- else {
458
- if (submitAttempts >= MAX_ATTEMPTS) {
459
- console.log(chalk.red(`\n✖ 连续 ${MAX_ATTEMPTS} 次验证未通过,为防止账号触发官方风控已主动终止。\n`));
460
- }
461
- else {
462
- console.log(chalk.red(`\n✖ 验证码提交未通过: ${submitRes.detail || '验证码错误或会话已过期'}\n`));
463
- }
464
- await safePressAnyKey();
465
- return;
466
- }
467
- }
468
- }
469
- else if (currentEvent === 'need_sms_code') {
470
- console.log(chalk.yellow(`\n📱 检测到手机二次短信验证 (${data.phoneMask || '••••'})`));
471
- const smsCode = (await safeInput({
472
- message: '请输入手机收到的短信验证码:',
473
- })) || '';
474
- if (smsCode) {
475
- console.log(chalk.cyan('正在提交手机验证码...'));
476
- const submitRes = await this.submitOtp(taskId, activeKey, smsCode);
477
- if (submitRes.ok && submitRes.token) {
478
- finishedToken = submitRes.token;
479
- if (submitRes.email)
480
- finishedEmail = submitRes.email;
481
- break;
482
- }
483
- }
484
- }
485
- else if (currentEvent === 'success') {
486
- finishedToken = data.token;
487
- if (data.email)
488
- finishedEmail = data.email;
489
- break;
490
- }
491
- else if (currentEvent === 'failed' || (data.error && currentEvent !== 'status')) {
492
- console.log(chalk.red(`\n✖ 代登未完成: ${data.error || data.detail || '官方服务响应超时或验证失败'}\n`));
493
- await safePressAnyKey();
494
- return;
559
+ catch (e) {
560
+ console.log(chalk.yellow(`本地浏览器唤起异常 (${e.message}),转入终端手动输入`));
561
+ }
562
+ }
563
+ else {
564
+ console.log(boxen([
565
+ chalk.bold.green('📨 Cursor 官方 6 位验证码已派发至您的邮箱!'),
566
+ chalk.dim('────────────────────────────────────────────────────────────'),
567
+ ` 接收邮箱 : ${chalk.bold.yellow(parsed.email)}`,
568
+ '',
569
+ chalk.bold.white('💡【取码指引】:'),
570
+ ` 1. 请打开/登录您的常用邮箱,查收来自 ${chalk.bold.cyan('Cursor')} 官方的 6 位数字验证码`,
571
+ ` 2. ${chalk.bold.yellow('特别注意: 若收件箱未看到邮件,请查看【其他 / Other】或【垃圾邮件】分类栏')}`,
572
+ ` 3. 复制收到的 6 位数字验证码,直接在下方粘贴并回车即可完成登录`,
573
+ ].join('\n'), {
574
+ padding: { top: 0, bottom: 0, left: 1, right: 1 },
575
+ borderColor: 'cyan',
576
+ borderStyle: 'round',
577
+ }));
578
+ }
579
+ let submitAttempts = 0;
580
+ const MAX_ATTEMPTS = 3;
581
+ while (submitAttempts < MAX_ATTEMPTS) {
582
+ const inputVal = (await safeInput({
583
+ message: submitAttempts === 0
584
+ ? '请输入收到的 6 位邮箱验证码 (可直接 Ctrl+V 粘贴):'
585
+ : `请重新输入 6 位验证码 (剩余 ${MAX_ATTEMPTS - submitAttempts} 次重试机会):`,
586
+ cancelHint: '输入 r 重发验证码,输入 0 或 q 取消',
587
+ })) || '';
588
+ if (!inputVal) {
589
+ return { action: 'abort', error: '未输入验证码,代登已终止。' };
590
+ }
591
+ if (inputVal.toLowerCase() === 'r' || inputVal.toLowerCase() === 'resend') {
592
+ console.log(chalk.cyan('\n⏳ 正在向 Cursor 申请重新发送最新验证码 (同会话重发,不扣额度)...'));
593
+ const resendRes = await this.resendCode(taskId, activeKey, parsed.email);
594
+ if (resendRes.ok) {
595
+ console.log(chalk.green(`✔ ${resendRes.message}`));
596
+ console.log(chalk.grey('提示: 请稍候 3~5 秒,并在收件箱(特别注意点击【其他】分类栏)查收新邮件。\n'));
597
+ }
598
+ else {
599
+ console.log(chalk.yellow(`⚠️ ${resendRes.message}\n`));
600
+ }
601
+ continue;
602
+ }
603
+ submitAttempts++;
604
+ console.log(chalk.cyan('正在提交验证码并生成官方登录凭证...'));
605
+ const submitRes = await this.submitOtp(taskId, activeKey, inputVal);
606
+ if (submitRes.ok) {
607
+ console.log(chalk.green('✔ 验证码已成功提交受理,等待云端签发 Token...'));
608
+ if (submitRes.token) {
609
+ return {
610
+ action: 'token',
611
+ token: submitRes.token,
612
+ accessToken: submitRes.accessToken,
613
+ refreshToken: submitRes.refreshToken,
614
+ email: submitRes.email,
615
+ };
616
+ }
617
+ return { action: 'wait_sse' };
618
+ }
619
+ else if (submitRes.needsSmsCode) {
620
+ console.log(chalk.yellow(`\n📱 检测到手机二次短信验证 (${submitRes.phoneMask || '••••'})`));
621
+ const smsCode = (await safeInput({ message: '请输入手机收到的短信验证码:' })) || '';
622
+ if (smsCode) {
623
+ console.log(chalk.cyan('正在提交手机验证码...'));
624
+ const smsRes = await this.submitOtp(taskId, activeKey, smsCode);
625
+ if (smsRes.ok && smsRes.token) {
626
+ return {
627
+ action: 'token',
628
+ token: smsRes.token,
629
+ accessToken: smsRes.accessToken,
630
+ refreshToken: smsRes.refreshToken,
631
+ email: smsRes.email,
632
+ };
495
633
  }
496
634
  }
497
- catch { }
635
+ return { action: 'wait_sse' };
636
+ }
637
+ else if (submitRes.canRetry && submitAttempts < MAX_ATTEMPTS) {
638
+ console.log(chalk.yellow(`\n⚠️ 验证码未通过: ${submitRes.detail || '验证码有误或网络抖动'}`));
639
+ const shouldRetry = await safeConfirm({
640
+ message: `当前代登会话仍有效,是否重新输入验证码?(还可重试 ${MAX_ATTEMPTS - submitAttempts} 次)`,
641
+ default: true,
642
+ });
643
+ if (shouldRetry) {
644
+ continue;
645
+ }
646
+ return { action: 'abort', error: '用户主动取消重试,代登已终止。' };
647
+ }
648
+ else {
649
+ const errMsg = submitAttempts >= MAX_ATTEMPTS
650
+ ? `连续 ${MAX_ATTEMPTS} 次验证未通过,为防止账号触发官方风控已主动终止。`
651
+ : `验证码提交未通过: ${submitRes.detail || '验证码错误或会话已过期'}`;
652
+ return { action: 'abort', error: errMsg };
498
653
  }
499
654
  }
500
- if (finishedToken)
501
- break;
502
- }
503
- }
504
- catch (err) {
505
- console.log(chalk.red(`\n事件监听断开: ${err.message}`));
506
- }
507
- // 5. 校验代登结果,严禁静默跳回主菜单
655
+ return { action: 'abort', error: '验证码提交次数已达上限,代登终止。' };
656
+ },
657
+ onNeedSmsCode: async (data) => {
658
+ console.log(chalk.yellow(`\n📱 检测到手机二次短信验证 (${data.phoneMask || '••••'})`));
659
+ const smsCode = (await safeInput({ message: '请输入手机收到的短信验证码:' })) || '';
660
+ if (smsCode) {
661
+ console.log(chalk.cyan('正在提交手机验证码...'));
662
+ const submitRes = await this.submitOtp(taskId, activeKey, smsCode);
663
+ if (submitRes.ok && submitRes.token) {
664
+ return {
665
+ action: 'token',
666
+ token: submitRes.token,
667
+ accessToken: submitRes.accessToken,
668
+ refreshToken: submitRes.refreshToken,
669
+ email: submitRes.email,
670
+ };
671
+ }
672
+ }
673
+ return { action: 'wait_sse' };
674
+ },
675
+ });
676
+ const finishedToken = streamRes.ok ? streamRes.token || null : null;
677
+ const finishedEmail = streamRes.email || parsed.email;
508
678
  if (!finishedToken) {
509
- console.log(chalk.yellow('\n⚠ 云端代登已结束,未捕获到有效 Token。'));
510
- console.log(chalk.grey('可能原因: 验证码录入耗时过长导致云端会话超时、或网络连接波动。'));
511
- console.log(chalk.grey('建议: 请检查邮箱验证码是否正确,在主菜单重新进入代登即可。\n'));
679
+ if (streamRes.error) {
680
+ console.log(chalk.red(`\n✖ 代登未完成: ${streamRes.error}\n`));
681
+ }
682
+ else {
683
+ console.log(chalk.yellow('\n⚠ 云端代登已结束,未捕获到有效 Token。'));
684
+ console.log(chalk.grey('可能原因: 验证码录入耗时过长导致云端会话超时、或网络连接波动。'));
685
+ console.log(chalk.grey('建议: 请检查邮箱验证码是否正确,在主菜单重新进入代登即可。\n'));
686
+ }
512
687
  await safePressAnyKey();
513
- return;
688
+ return null;
514
689
  }
515
- console.log(chalk.green.bold('\n🎉 纯净代登成功!官方凭据已安全捕获!'));
516
- const parsedToken = TokenParser.parse(finishedToken);
517
- const machineIds = generateMachineIds();
518
- // 同步查询官方额度与会员身份
519
- console.log(chalk.grey('正在同步官方用量与订阅计划...'));
520
- const usageRes = await OfficialApiClient.fetchUsage(parsedToken.token);
521
- const existing = store.getByEmail(finishedEmail);
522
- const newAccount = {
690
+ console.log(chalk.green.bold('\n🎉 纯净代登成功!官方凭据已获取!'));
691
+ console.log(chalk.grey('正在同步官方用量与订阅计划并保存凭据...'));
692
+ const { account: newAccount, machineIds } = await this.saveExtractedAccount(store, {
523
693
  email: finishedEmail,
524
694
  token: finishedToken,
525
- workos_cursor_session_token: parsedToken.workosSessionToken || finishedToken,
526
- subscription_type: usageRes.success && usageRes.subscriptionType ? usageRes.subscriptionType : (existing?.subscription_type || 'free'),
527
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
528
- machine_ids: machineIds,
529
- email_password: parsed.emailPassword,
530
- cursor_password: parsed.cursorPassword,
531
- };
532
- store.addOrUpdate(newAccount);
533
- // 自动写入系统剪贴板
534
- const copied = await copyToClipboard(finishedToken);
535
- console.log(boxen([
536
- chalk.bold.green('✔ 账号已收录入库!'),
537
- chalk.dim('────────────────────────────────────────────────'),
538
- ` 登录邮箱 : ${chalk.bold.white(newAccount.email)}`,
539
- ` 会员级别 : ${formatPlanBadge(newAccount.subscription_type)}`,
540
- ` 专属指纹 : ${chalk.cyan(formatMachineIdSummary(machineIds))}`,
541
- ` 剪贴板 : ${copied ? chalk.green('● 完整 Token 已自动复制到系统剪贴板 (随时 Ctrl+V 粘贴)') : chalk.yellow('○ 剪贴板未生效,请在下方直接选中复制')}`,
542
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
543
- console.log(chalk.bold.white('\n📋 官方完整 Token (点击或拖选即可复制):'));
544
- console.log(chalk.cyan(finishedToken) + '\n');
545
- // 询问是否立即切换
695
+ accessToken: streamRes.accessToken,
696
+ refreshToken: streamRes.refreshToken,
697
+ emailPassword: parsed.emailPassword,
698
+ cursorPassword: parsed.cursorPassword,
699
+ });
700
+ await printExtractedCredentialsResult({
701
+ header: '✔ 账号已收录入库!',
702
+ account: newAccount,
703
+ machineIds,
704
+ configStore: this.configStore,
705
+ showPlaintext: false,
706
+ });
707
+ if (options.skipSwitchPrompt) {
708
+ return newAccount;
709
+ }
546
710
  const doSwitch = await safeConfirm({
547
711
  message: `是否立即切换到该账号 (${newAccount.email}) 并激活专属指纹?`,
548
712
  default: true,
549
713
  });
550
714
  if (doSwitch) {
551
715
  console.log(chalk.cyan(`\n正在执行换号流程,目标: ${chalk.bold.white(newAccount.email)} ...`));
552
- if (ProcessManager.isCursorRunning()) {
553
- console.log(chalk.grey('✔ [1/4] 发送退出信号,释放 SQLite 独占锁'));
554
- await ProcessManager.closeCursor();
716
+ const swRes = await executeAccountSwitch({
717
+ store,
718
+ storage,
719
+ sqlite,
720
+ targetAccount: newAccount,
721
+ onStep: (step, detail) => {
722
+ if (step === 'close' && detail === 'running') {
723
+ console.log(chalk.grey('✔ [1/4] 发送退出信号,释放 SQLite 独占锁'));
724
+ }
725
+ else if (step === 'backup') {
726
+ console.log(chalk.grey('✔ [2/4] 创建本地安全快照备份'));
727
+ }
728
+ else if (step === 'machine') {
729
+ console.log(chalk.grey(`✔ [3/4] 装载专属防封机器指纹: ${formatMachineIdSummary(machineIds)}`));
730
+ }
731
+ else if (step === 'auth') {
732
+ console.log(chalk.grey('✔ [4/4] 清旧并原子注入新凭据与侧车配置'));
733
+ }
734
+ },
735
+ });
736
+ if (swRes.aborted) {
737
+ console.log(chalk.yellow('\n已取消切换,本机 Cursor 登录态未作修改。\n'));
555
738
  }
556
- storage.createBackup();
557
- sqlite.createBackup();
558
- console.log(chalk.grey('✔ [2/4] 创建本地安全快照备份'));
559
- storage.writeMachineIds(machineIds);
560
- console.log(chalk.grey(`✔ [3/4] 装载专属防封机器指纹: ${formatMachineIdSummary(machineIds)}`));
561
- const tokenPart = TokenParser.extractTokenPart(newAccount.token);
562
- const refreshToken = newAccount.workos_cursor_session_token || tokenPart;
563
- storage.writeAuth(newAccount.email, tokenPart, refreshToken);
564
- await sqlite.injectAuth(newAccount.email, tokenPart, refreshToken);
565
- store.markCurrent(newAccount.email);
566
- console.log(chalk.grey('✔ [4/4] 原子注入 Token 到 SQLite 数据库'));
567
- console.log(chalk.green(`\n✔ 换号成功!当前账号: ${chalk.bold.white(newAccount.email)}\n`));
568
- if (executablePath) {
569
- const needRelaunch = await safeConfirm({
570
- message: '是否立即重新启动 Cursor IDE?',
571
- default: true,
572
- });
573
- if (needRelaunch) {
574
- ProcessManager.launchCursor(executablePath);
575
- console.log(chalk.green('✔ Cursor 已在后台启动'));
739
+ else {
740
+ if (swRes.refreshed) {
741
+ console.log(chalk.green('✔ 已自动完成 OAuth Refresh Token 续期'));
742
+ }
743
+ for (const w of swRes.warnings) {
744
+ console.log(chalk.yellow(`⚠ ${w}`));
745
+ }
746
+ console.log(chalk.green(`\n✔ 换号成功!当前账号: ${chalk.bold.white(newAccount.email)}\n`));
747
+ if (executablePath) {
748
+ const needRelaunch = await safeConfirm({
749
+ message: '是否立即重新启动 Cursor IDE?',
750
+ default: true,
751
+ });
752
+ if (needRelaunch) {
753
+ ProcessManager.launchCursor(executablePath);
754
+ console.log(chalk.green('✔ Cursor 已在后台启动'));
755
+ }
576
756
  }
577
757
  }
578
758
  }
579
759
  await safePressAnyKey();
760
+ return newAccount;
580
761
  }
581
762
  }