cursor-switch 1.0.7 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +76 -75
  2. package/SECURITY.md +22 -19
  3. package/bin/cswitch.js +31 -8
  4. package/dist/cli.d.ts +0 -4
  5. package/dist/cli.js +404 -241
  6. package/dist/core/account-store.d.ts +0 -7
  7. package/dist/core/account-store.js +22 -28
  8. package/dist/core/cdp-engine.d.ts +11 -49
  9. package/dist/core/cdp-engine.js +155 -110
  10. package/dist/core/config-store.d.ts +7 -6
  11. package/dist/core/config-store.js +33 -12
  12. package/dist/core/cursor-paths.d.ts +8 -18
  13. package/dist/core/cursor-paths.js +18 -37
  14. package/dist/core/dashboard-launcher.d.ts +0 -20
  15. package/dist/core/dashboard-launcher.js +3 -53
  16. package/dist/core/extract-client.d.ts +57 -0
  17. package/dist/core/extract-client.js +219 -0
  18. package/dist/core/extract-menu.d.ts +3 -0
  19. package/dist/core/extract-menu.js +360 -0
  20. package/dist/core/extract-service.d.ts +64 -0
  21. package/dist/core/extract-service.js +435 -0
  22. package/dist/core/fingerprint.d.ts +0 -4
  23. package/dist/core/fingerprint.js +0 -6
  24. package/dist/core/oauth-receiver.d.ts +1 -11
  25. package/dist/core/oauth-receiver.js +509 -527
  26. package/dist/core/official-api.d.ts +0 -17
  27. package/dist/core/official-api.js +4 -23
  28. package/dist/core/outlook-launcher.d.ts +0 -31
  29. package/dist/core/outlook-launcher.js +194 -248
  30. package/dist/core/process-manager.d.ts +0 -14
  31. package/dist/core/process-manager.js +7 -22
  32. package/dist/core/pure-login-service.d.ts +54 -38
  33. package/dist/core/pure-login-service.js +483 -395
  34. package/dist/core/refund-client.d.ts +0 -22
  35. package/dist/core/refund-client.js +7 -27
  36. package/dist/core/refund-service.d.ts +0 -16
  37. package/dist/core/refund-service.js +8 -34
  38. package/dist/core/safe-storage.d.ts +27 -0
  39. package/dist/core/safe-storage.js +284 -0
  40. package/dist/core/sqlite-bridge.d.ts +10 -11
  41. package/dist/core/sqlite-bridge.js +112 -47
  42. package/dist/core/storage-bridge.d.ts +14 -5
  43. package/dist/core/storage-bridge.js +84 -24
  44. package/dist/core/switch-orchestrator.d.ts +96 -0
  45. package/dist/core/switch-orchestrator.js +341 -0
  46. package/dist/core/token-exchange.d.ts +81 -0
  47. package/dist/core/token-exchange.js +275 -0
  48. package/dist/core/token-parser.d.ts +56 -20
  49. package/dist/core/token-parser.js +354 -43
  50. package/dist/core/update-checker.d.ts +1 -29
  51. package/dist/core/update-checker.js +28 -43
  52. package/dist/index.d.ts +1 -3
  53. package/dist/index.js +1 -3
  54. package/dist/menu.d.ts +0 -7
  55. package/dist/menu.js +445 -548
  56. package/dist/types.d.ts +12 -4
  57. package/dist/types.js +0 -4
  58. package/dist/utils/account-text-importer.d.ts +9 -0
  59. package/dist/utils/account-text-importer.js +96 -0
  60. package/dist/utils/browser-utils.d.ts +0 -24
  61. package/dist/utils/browser-utils.js +0 -57
  62. package/dist/utils/clipboard.d.ts +0 -4
  63. package/dist/utils/clipboard.js +0 -5
  64. package/dist/utils/credential-bundle-ui.d.ts +36 -0
  65. package/dist/utils/credential-bundle-ui.js +246 -0
  66. package/dist/utils/live-menu.d.ts +37 -9
  67. package/dist/utils/live-menu.js +510 -81
  68. package/dist/utils/plan-formatter.d.ts +0 -26
  69. package/dist/utils/plan-formatter.js +10 -44
  70. package/dist/utils/prompt-utils.d.ts +0 -18
  71. package/dist/utils/prompt-utils.js +0 -23
  72. package/dist/utils/proxy-bootstrap.d.ts +12 -0
  73. package/dist/utils/proxy-bootstrap.js +141 -0
  74. package/dist/utils/security.d.ts +2 -4
  75. package/dist/utils/security.js +36 -4
  76. package/dist/utils/table-renderer.d.ts +0 -4
  77. package/dist/utils/table-renderer.js +24 -8
  78. package/dist/utils/time-formatter.d.ts +0 -4
  79. package/dist/utils/time-formatter.js +0 -8
  80. package/dist/utils/token-preflight-ui.d.ts +28 -0
  81. package/dist/utils/token-preflight-ui.js +222 -0
  82. package/dist/utils/window-focus.d.ts +3 -0
  83. package/dist/utils/window-focus.js +106 -0
  84. package/package.json +12 -5
  85. package/dist/core/welcome-offer-service.d.ts +0 -52
  86. package/dist/core/welcome-offer-service.js +0 -369
@@ -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,15 +197,12 @@ 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
- * 向云端申请重新发送验证码 (同会话重发,不扣减卡密额度)
185
- */
186
204
  async resendCode(taskId, cardCode, email) {
187
- const apiBase = this.configStore.getSeatApiBase();
205
+ const apiBase = this.getApiBase();
188
206
  try {
189
207
  const res = await fetch(`${apiBase}/api/v1/token-service/resend-code`, {
190
208
  method: 'POST',
@@ -194,6 +212,7 @@ export class PureLoginService {
194
212
  card_code: cardCode.trim(),
195
213
  email: email.trim(),
196
214
  }),
215
+ signal: AbortSignal.timeout(15000),
197
216
  });
198
217
  const data = await res.json().catch(() => ({}));
199
218
  if (res.ok && data.success) {
@@ -202,88 +221,218 @@ export class PureLoginService {
202
221
  return { ok: false, message: data.detail || data.error || '重新请求发信失败,请稍后重试' };
203
222
  }
204
223
  catch (err) {
205
- return { ok: false, message: `网络连接异常: ${err.message}` };
224
+ return { ok: false, message: `网络连接异常: ${formatNetworkError(err)}` };
206
225
  }
207
226
  }
208
- /**
209
- * 结构化查询云端邮箱验证码并精准解析是否可重试
210
- */
211
- async fetchMailCodeResult(email, emailPassword, cursorPassword) {
212
- const apiBase = this.configStore.getSeatApiBase();
227
+ async cancelTask(taskId, cardCode) {
228
+ const apiBase = this.getApiBase();
213
229
  try {
214
- const res = await fetch(`${apiBase}/api/v1/mail/code`, {
230
+ await fetch(`${apiBase}/api/v1/token-service/cancel`, {
215
231
  method: 'POST',
216
232
  headers: { 'Content-Type': 'application/json' },
217
233
  body: JSON.stringify({
218
- account: email.trim(),
219
- emailPassword: emailPassword.trim(),
220
- cursorPassword: cursorPassword?.trim() || '',
234
+ task_id: taskId,
235
+ card_code: cardCode.trim(),
221
236
  }),
237
+ signal: AbortSignal.timeout(4000),
222
238
  });
223
- const data = await res.json().catch(() => ({}));
224
- if (res.ok) {
225
- let code = '';
226
- if (data.code && /^\d{6}$/.test(data.code)) {
227
- code = data.code;
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;
228
310
  }
229
- else if (Array.isArray(data.mails)) {
230
- for (const m of data.mails) {
231
- const text = `${m.subject || ''} ${m.body || m.content || ''}`;
232
- const match = text.match(/\b\d{6}\b/);
233
- if (match) {
234
- code = match[0];
235
- break;
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
+ }
236
413
  }
414
+ catch { }
237
415
  }
238
416
  }
239
- if (code) {
240
- return { ok: true, code, retryable: false, message: '取码成功' };
241
- }
242
- // data.retryable 由后端严格判定:
243
- // 若密码错误/令牌未匹配/账号不存在,后端返回 retryable: false
244
- // 只有收件箱暂无新邮件时,后端返回 retryable: true
245
- const retryable = Boolean(data.retryable !== false && (data.ok === true || data.ok === undefined));
246
- return {
247
- ok: Boolean(data.ok),
248
- code: '',
249
- retryable,
250
- message: data.message || (retryable ? '收件箱暂无新邮件' : '邮箱不存在或密码不正确'),
251
- };
252
417
  }
253
- else {
254
- // HTTP 429 属于限流(稍后可重试),而 400/403/404/401 属于不可重试的致命错误
255
- const retryable = res.status === 429;
256
- return {
257
- ok: false,
258
- code: '',
259
- retryable,
260
- message: data.detail || data.message || `云端服务返回异常 (HTTP ${res.status})`,
261
- };
418
+ if (!terminalResult && pendingHandler) {
419
+ await pendingHandler;
420
+ }
421
+ try {
422
+ await reader.cancel();
262
423
  }
424
+ catch { }
263
425
  }
264
426
  catch (err) {
265
- return {
266
- ok: false,
267
- code: '',
268
- retryable: true,
269
- message: `网络连接异常: ${err.message}`,
270
- };
427
+ if (!terminalResult && !abortController.signal.aborted) {
428
+ return { ok: false, error: `事件监听断开: ${formatNetworkError(err)}` };
429
+ }
271
430
  }
431
+ return terminalResult || { ok: false, error: '云端代登已结束,未捕获到有效 Token' };
272
432
  }
273
- /**
274
- * 自动从用户邮箱中提取最新 6 位数字验证码 (保留兼容性)
275
- */
276
- async autoFetchMailCode(email, emailPassword, cursorPassword) {
277
- const res = await this.fetchMailCodeResult(email, emailPassword, cursorPassword);
278
- return res.code || null;
279
- }
280
- /**
281
- * 交互式运行纯净代登全流程 (终端交互式 TUI)
282
- */
283
433
  async runInteractiveFlow(store, storage, sqlite, executablePath, options = {}) {
284
- console.log(chalk.bold.cyan('\n☁ 正在连接海外纯净代登云服务...\n'));
285
- console.log(chalk.grey('说明: 100% 云端集群托管执行,本地无需安装代理,全自动过人机盾/收信取码提取 Token。\n'));
286
- // 1. 获取并核验代登卡密 (自动读取记忆,支持一键复用或更换)
434
+ console.log(chalk.bold.cyan('\n☁ 正在连接 Cursor 纯净代登服务...\n'));
435
+ console.log(chalk.grey('说明: 通过独立代理环境辅助登录,录入邮箱验证码获取 Token(若账号自身触发手机短信风控则无法仅凭邮箱登录;启动即扣 1 次额度,失败不退)。\n'));
287
436
  const savedKey = this.configStore.getTokenCardCode() || this.configStore.getSeatCardCode();
288
437
  let activeKey = '';
289
438
  if (savedKey) {
@@ -322,7 +471,6 @@ export class PureLoginService {
322
471
  }
323
472
  }
324
473
  }
325
- // 2. 录入待登账号信息 (支持直接输入邮箱,或粘贴带分隔符的账号)
326
474
  let rawInput = options.prefilledInput?.trim();
327
475
  if (!rawInput) {
328
476
  console.log(chalk.grey('提示: 请输入待登 Cursor 邮箱 (支持直接粘贴 user@outlook.com 或 user@outlook.com----xxx 格式):'));
@@ -342,18 +490,16 @@ export class PureLoginService {
342
490
  chalk.bold.white('📋 账号待登要素确认:'),
343
491
  chalk.dim('────────────────────────────────────────────────'),
344
492
  ` 目标邮箱 : ${chalk.bold.yellow(parsed.email)}`,
345
- ` 代登模式 : ${chalk.cyan('⚡ 纯净海外住宅 IP 专线代登')}`,
493
+ ` 代登模式 : ${chalk.cyan('⚡ 云端代理辅助登录')}`,
346
494
  ` 取码方式 : ${chalk.green('💬 查收邮件并在终端输入 6 位验证码')}`,
347
495
  ...(parsed.cursorPassword ? [` 附加信息 : ${chalk.grey('● 已保留备用')}`] : []),
348
496
  ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'blue', borderStyle: 'round' }));
349
- // 3. 启动云端任务并建立 SSE 流式监听
350
- console.log(chalk.cyan('\n正在连接海外住宅集群分配独享出口 IP 并启动任务...'));
497
+ console.log(chalk.cyan('\n正在分配云端代登环境并启动任务...'));
351
498
  const startRes = await this.startTask({
352
499
  code: activeKey,
353
500
  email: parsed.email,
354
501
  emailPassword: parsed.emailPassword,
355
502
  cursorPassword: parsed.cursorPassword,
356
- rawAccount: rawInput,
357
503
  });
358
504
  if (!startRes.ok || !startRes.taskId) {
359
505
  console.log(chalk.red(`\n✖ 任务启动失败: ${startRes.detail || '未知原因'}\n`));
@@ -362,309 +508,251 @@ export class PureLoginService {
362
508
  }
363
509
  const taskId = startRes.taskId;
364
510
  console.log(chalk.green(`✔ 任务已受理 (TaskID: ${taskId.slice(0, 8)}),正在实时处理...\n`));
365
- // 4. 监听 SSE 事件流
366
- const apiBase = this.configStore.getSeatApiBase();
367
- let finishedToken = null;
368
- let finishedEmail = parsed.email;
369
- try {
370
- const tokenQuery = startRes.taskToken ? `?token=${encodeURIComponent(startRes.taskToken)}` : '';
371
- const sseRes = await fetch(`${apiBase}/api/v1/token-service/events/${taskId}${tokenQuery}`, {
372
- headers: { Accept: 'text/event-stream' },
373
- });
374
- if (!sseRes.ok || !sseRes.body) {
375
- throw new Error(`SSE 状态连接异常 (HTTP ${sseRes.status})`);
376
- }
377
- const reader = sseRes.body.getReader();
378
- const decoder = new TextDecoder();
379
- let buffer = '';
380
- let currentEvent = 'message';
381
- while (true) {
382
- const { done, value } = await reader.read();
383
- if (done)
384
- break;
385
- buffer += decoder.decode(value, { stream: true });
386
- const lines = buffer.split(/\r?\n/);
387
- buffer = lines.pop() || '';
388
- for (const line of lines) {
389
- if (line.startsWith('event:')) {
390
- 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
+ }
391
558
  }
392
- else if (line.startsWith('data:')) {
393
- const dataStr = line.replace(/^data:\s*/, '').trim();
394
- if (!dataStr)
395
- continue;
396
- try {
397
- const data = JSON.parse(dataStr);
398
- // 优先检测是否直接携带了 Token
399
- if (data.token) {
400
- finishedToken = data.token;
401
- if (data.email)
402
- finishedEmail = data.email;
403
- break;
404
- }
405
- if (currentEvent === 'status') {
406
- const step = data.step ? `[${data.step}] ` : '';
407
- console.log(chalk.grey(`⏳ ${step}${data.msg || '正在推进登录鉴权...'}`));
408
- }
409
- else if (currentEvent === 'need_code') {
410
- console.log(chalk.yellow(`\n📨 Cursor 验证码已派发至您的邮箱 (${parsed.email})`));
411
- // 若提供了邮箱密码,调起本地独立隔离浏览器协助自动登录 Outlook
412
- if (parsed.emailPassword) {
413
- console.log(chalk.cyan('🚀 正在启动本地独立隔离浏览器,自动登录 Outlook 邮箱...'));
414
- try {
415
- const mailRes = await OutlookLauncher.openMailbox({
416
- email: parsed.email,
417
- emailPassword: parsed.emailPassword,
418
- sniffOtp: false, // 零等待,秒登进入后直接置顶
419
- });
420
- if (mailRes.status === 'logged_in') {
421
- console.log(boxen([
422
- chalk.bold.green('✔ 独立浏览器已自动登入 Outlook 收件箱!'),
423
- chalk.dim('────────────────────────────────────────────────────────────'),
424
- chalk.bold.white('💡【取码指引】:'),
425
- ` 1. 浏览器窗口已置顶展示,请查看最新的 ${chalk.bold.cyan('Cursor')} 官方邮件`,
426
- ` 2. ${chalk.bold.yellow('特别注意: 若收件箱未看到邮件,请务必点击上方【其他 / Other】分类栏')}`,
427
- ` 3. 复制或记下邮件中的 6 位数字验证码,直接在下方粘贴/输入`,
428
- ].join('\n'), {
429
- padding: { top: 0, bottom: 0, left: 1, right: 1 },
430
- borderColor: 'green',
431
- borderStyle: 'round',
432
- }));
433
- }
434
- else if (mailRes.status === 'manual_required') {
435
- console.log(boxen([
436
- chalk.bold.yellow('⚠️ 微软要求安全验证 (辅助邮箱 / 二次认证)'),
437
- chalk.dim('────────────────────────────────────────────────────────────'),
438
- ` • 浏览器窗口已为您调起并置顶,请在浏览器中完成辅助邮箱验证`,
439
- ` • 验证成功进入收件箱后,查看最新的 ${chalk.bold.cyan('Cursor')} 验证码并在下方输入`,
440
- ` • ${chalk.dim('提示: 若收件箱未看到邮件,请查看【其他】分类栏')}`,
441
- ].join('\n'), {
442
- padding: { top: 0, bottom: 0, left: 1, right: 1 },
443
- borderColor: 'yellow',
444
- borderStyle: 'round',
445
- }));
446
- }
447
- else {
448
- console.log(chalk.grey(` → 浏览器状态: ${mailRes.message}`));
449
- }
450
- }
451
- catch (e) {
452
- console.log(chalk.yellow(`本地浏览器唤起异常 (${e.message}),转入终端手动输入`));
453
- }
454
- }
455
- else {
456
- console.log(boxen([
457
- chalk.bold.green('📨 Cursor 官方 6 位验证码已派发至您的邮箱!'),
458
- chalk.dim('────────────────────────────────────────────────────────────'),
459
- ` 接收邮箱 : ${chalk.bold.yellow(parsed.email)}`,
460
- '',
461
- chalk.bold.white('💡【取码指引】:'),
462
- ` 1. 请打开/登录您的常用邮箱,查收来自 ${chalk.bold.cyan('Cursor')} 官方的 6 位数字验证码`,
463
- ` 2. ${chalk.bold.yellow('特别注意: 若收件箱未看到邮件,请查看【其他 / Other】或【垃圾邮件】分类栏')}`,
464
- ` 3. 复制收到的 6 位数字验证码,直接在下方粘贴并回车即可完成登录`,
465
- ].join('\n'), {
466
- padding: { top: 0, bottom: 0, left: 1, right: 1 },
467
- borderColor: 'cyan',
468
- borderStyle: 'round',
469
- }));
470
- }
471
- let otpToSubmit = '';
472
- let submitAttempts = 0;
473
- const MAX_ATTEMPTS = 3;
474
- while (submitAttempts < MAX_ATTEMPTS) {
475
- const inputVal = (await safeInput({
476
- message: submitAttempts === 0
477
- ? '请输入收到的 6 位邮箱验证码 (可直接 Ctrl+V 粘贴):'
478
- : `请重新输入 6 位验证码 (剩余 ${MAX_ATTEMPTS - submitAttempts} 次重试机会):`,
479
- cancelHint: '输入 r 重发验证码,输入 0 或 q 取消',
480
- })) || '';
481
- if (!inputVal) {
482
- console.log(chalk.red('\n未输入验证码,代登已终止。\n'));
483
- await safePressAnyKey();
484
- return null;
485
- }
486
- // 支持输入 r / resend 重发验证码 (同会话重发,不扣减卡密额度)
487
- if (inputVal.toLowerCase() === 'r' || inputVal.toLowerCase() === 'resend') {
488
- console.log(chalk.cyan('\n⏳ 正在向 Cursor 申请重新发送最新验证码 (同会话重发,不扣额度)...'));
489
- const resendRes = await this.resendCode(taskId, activeKey, parsed.email);
490
- if (resendRes.ok) {
491
- console.log(chalk.green(`✔ ${resendRes.message}`));
492
- console.log(chalk.grey('提示: 请稍候 3~5 秒,并在收件箱(特别注意点击【其他】分类栏)查收新邮件。\n'));
493
- }
494
- else {
495
- console.log(chalk.yellow(`⚠️ ${resendRes.message}\n`));
496
- }
497
- continue;
498
- }
499
- otpToSubmit = inputVal;
500
- submitAttempts++;
501
- console.log(chalk.cyan('正在提交验证码并生成官方登录凭证...'));
502
- const submitRes = await this.submitOtp(taskId, activeKey, otpToSubmit);
503
- if (submitRes.ok) {
504
- console.log(chalk.green('✔ 验证码已成功提交受理,等待云端签发 Token...'));
505
- if (submitRes.token) {
506
- finishedToken = submitRes.token;
507
- if (submitRes.email)
508
- finishedEmail = submitRes.email;
509
- break;
510
- }
511
- break;
512
- }
513
- else if (submitRes.needsSmsCode) {
514
- console.log(chalk.yellow(`\n📱 检测到手机二次短信验证 (${submitRes.phoneMask || '••••'})`));
515
- const smsCode = (await safeInput({
516
- message: '请输入手机收到的短信验证码:',
517
- })) || '';
518
- if (smsCode) {
519
- console.log(chalk.cyan('正在提交手机验证码...'));
520
- const smsRes = await this.submitOtp(taskId, activeKey, smsCode);
521
- if (smsRes.ok && smsRes.token) {
522
- finishedToken = smsRes.token;
523
- if (smsRes.email)
524
- finishedEmail = smsRes.email;
525
- break;
526
- }
527
- }
528
- break;
529
- }
530
- else if (submitRes.canRetry && submitAttempts < MAX_ATTEMPTS) {
531
- console.log(chalk.yellow(`\n⚠️ 验证码未通过: ${submitRes.detail || '验证码有误或网络抖动'}`));
532
- const shouldRetry = await safeConfirm({
533
- message: `当前代登会话仍有效,是否重新输入验证码?(还可重试 ${MAX_ATTEMPTS - submitAttempts} 次)`,
534
- default: true,
535
- });
536
- if (shouldRetry) {
537
- otpToSubmit = '';
538
- continue;
539
- }
540
- else {
541
- console.log(chalk.grey('\n用户主动取消重试,代登已终止。\n'));
542
- await safePressAnyKey();
543
- return null;
544
- }
545
- }
546
- else {
547
- if (submitAttempts >= MAX_ATTEMPTS) {
548
- console.log(chalk.red(`\n✖ 连续 ${MAX_ATTEMPTS} 次验证未通过,为防止账号触发官方风控已主动终止。\n`));
549
- }
550
- else {
551
- console.log(chalk.red(`\n✖ 验证码提交未通过: ${submitRes.detail || '验证码错误或会话已过期'}\n`));
552
- }
553
- await safePressAnyKey();
554
- return null;
555
- }
556
- }
557
- }
558
- else if (currentEvent === 'need_sms_code') {
559
- console.log(chalk.yellow(`\n📱 检测到手机二次短信验证 (${data.phoneMask || '••••'})`));
560
- const smsCode = (await safeInput({
561
- message: '请输入手机收到的短信验证码:',
562
- })) || '';
563
- if (smsCode) {
564
- console.log(chalk.cyan('正在提交手机验证码...'));
565
- const submitRes = await this.submitOtp(taskId, activeKey, smsCode);
566
- if (submitRes.ok && submitRes.token) {
567
- finishedToken = submitRes.token;
568
- if (submitRes.email)
569
- finishedEmail = submitRes.email;
570
- break;
571
- }
572
- }
573
- }
574
- else if (currentEvent === 'success') {
575
- finishedToken = data.token;
576
- if (data.email)
577
- finishedEmail = data.email;
578
- break;
579
- }
580
- else if (currentEvent === 'failed' || (data.error && currentEvent !== 'status')) {
581
- console.log(chalk.red(`\n✖ 代登未完成: ${data.error || data.detail || '官方服务响应超时或验证失败'}\n`));
582
- await safePressAnyKey();
583
- return null;
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
+ };
584
633
  }
585
634
  }
586
- 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 };
587
653
  }
588
654
  }
589
- if (finishedToken)
590
- break;
591
- }
592
- }
593
- catch (err) {
594
- console.log(chalk.red(`\n事件监听断开: ${err.message}`));
595
- }
596
- // 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;
597
678
  if (!finishedToken) {
598
- console.log(chalk.yellow('\n⚠ 云端代登已结束,未捕获到有效 Token。'));
599
- console.log(chalk.grey('可能原因: 验证码录入耗时过长导致云端会话超时、或网络连接波动。'));
600
- 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
+ }
601
687
  await safePressAnyKey();
602
688
  return null;
603
689
  }
604
- console.log(chalk.green.bold('\n🎉 纯净代登成功!官方凭据已安全捕获!'));
605
- const parsedToken = TokenParser.parse(finishedToken);
606
- const machineIds = generateMachineIds();
607
- // 同步查询官方额度与会员身份
608
- console.log(chalk.grey('正在同步官方用量与订阅计划...'));
609
- const usageRes = await OfficialApiClient.fetchUsage(parsedToken.token);
610
- const existing = store.getByEmail(finishedEmail);
611
- const newAccount = {
690
+ console.log(chalk.green.bold('\n🎉 纯净代登成功!官方凭据已获取!'));
691
+ console.log(chalk.grey('正在同步官方用量与订阅计划并保存凭据...'));
692
+ const { account: newAccount, machineIds } = await this.saveExtractedAccount(store, {
612
693
  email: finishedEmail,
613
694
  token: finishedToken,
614
- workos_cursor_session_token: parsedToken.workosSessionToken || finishedToken,
615
- subscription_type: usageRes.success && usageRes.subscriptionType ? usageRes.subscriptionType : (existing?.subscription_type || 'free'),
616
- current_period_usage: usageRes.currentPeriodUsage || existing?.current_period_usage,
617
- machine_ids: machineIds,
618
- email_password: parsed.emailPassword,
619
- cursor_password: parsed.cursorPassword,
620
- };
621
- store.addOrUpdate(newAccount);
622
- // 自动写入系统剪贴板
623
- const copied = await copyToClipboard(finishedToken);
624
- console.log(boxen([
625
- chalk.bold.green('✔ 账号已收录入库!'),
626
- chalk.dim('────────────────────────────────────────────────'),
627
- ` 登录邮箱 : ${chalk.bold.white(newAccount.email)}`,
628
- ` 会员级别 : ${formatPlanBadge(newAccount.subscription_type)}`,
629
- ` 专属指纹 : ${chalk.cyan(formatMachineIdSummary(machineIds))}`,
630
- ` 剪贴板 : ${copied ? chalk.green('● 完整 Token 已自动复制到系统剪贴板 (随时 Ctrl+V 粘贴)') : chalk.yellow('○ 剪贴板未生效,请在下方直接选中复制')}`,
631
- ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round' }));
632
- console.log(chalk.bold.white('\n📋 官方完整 Token (点击或拖选即可复制):'));
633
- console.log(chalk.cyan(finishedToken) + '\n');
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
+ });
634
707
  if (options.skipSwitchPrompt) {
635
708
  return newAccount;
636
709
  }
637
- // 询问是否立即切换
638
710
  const doSwitch = await safeConfirm({
639
711
  message: `是否立即切换到该账号 (${newAccount.email}) 并激活专属指纹?`,
640
712
  default: true,
641
713
  });
642
714
  if (doSwitch) {
643
715
  console.log(chalk.cyan(`\n正在执行换号流程,目标: ${chalk.bold.white(newAccount.email)} ...`));
644
- if (ProcessManager.isCursorRunning()) {
645
- console.log(chalk.grey('✔ [1/4] 发送退出信号,释放 SQLite 独占锁'));
646
- 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'));
647
738
  }
648
- storage.createBackup();
649
- sqlite.createBackup();
650
- console.log(chalk.grey('✔ [2/4] 创建本地安全快照备份'));
651
- storage.writeMachineIds(machineIds);
652
- console.log(chalk.grey(`✔ [3/4] 装载专属防封机器指纹: ${formatMachineIdSummary(machineIds)}`));
653
- const tokenPart = TokenParser.extractTokenPart(newAccount.token);
654
- const refreshToken = newAccount.workos_cursor_session_token || tokenPart;
655
- storage.writeAuth(newAccount.email, tokenPart, refreshToken);
656
- await sqlite.injectAuth(newAccount.email, tokenPart, refreshToken);
657
- store.markCurrent(newAccount.email);
658
- console.log(chalk.grey('✔ [4/4] 原子注入 Token 到 SQLite 数据库'));
659
- console.log(chalk.green(`\n✔ 换号成功!当前账号: ${chalk.bold.white(newAccount.email)}\n`));
660
- if (executablePath) {
661
- const needRelaunch = await safeConfirm({
662
- message: '是否立即重新启动 Cursor IDE?',
663
- default: true,
664
- });
665
- if (needRelaunch) {
666
- ProcessManager.launchCursor(executablePath);
667
- 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
+ }
668
756
  }
669
757
  }
670
758
  }