cursor-switch 1.0.0

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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +161 -0
  3. package/SECURITY.md +38 -0
  4. package/bin/cswitch.js +35 -0
  5. package/dist/cli.d.ts +6 -0
  6. package/dist/cli.js +850 -0
  7. package/dist/core/account-store.d.ts +25 -0
  8. package/dist/core/account-store.js +182 -0
  9. package/dist/core/cdp-engine.d.ts +75 -0
  10. package/dist/core/cdp-engine.js +320 -0
  11. package/dist/core/config-store.d.ts +38 -0
  12. package/dist/core/config-store.js +100 -0
  13. package/dist/core/cursor-paths.d.ts +22 -0
  14. package/dist/core/cursor-paths.js +287 -0
  15. package/dist/core/dashboard-launcher.d.ts +34 -0
  16. package/dist/core/dashboard-launcher.js +210 -0
  17. package/dist/core/fingerprint.d.ts +7 -0
  18. package/dist/core/fingerprint.js +34 -0
  19. package/dist/core/oauth-receiver.d.ts +31 -0
  20. package/dist/core/oauth-receiver.js +849 -0
  21. package/dist/core/official-api.d.ts +29 -0
  22. package/dist/core/official-api.js +205 -0
  23. package/dist/core/outlook-launcher.d.ts +54 -0
  24. package/dist/core/outlook-launcher.js +671 -0
  25. package/dist/core/process-manager.d.ts +25 -0
  26. package/dist/core/process-manager.js +133 -0
  27. package/dist/core/pure-login-service.d.ts +67 -0
  28. package/dist/core/pure-login-service.js +550 -0
  29. package/dist/core/refund-client.d.ts +102 -0
  30. package/dist/core/refund-client.js +221 -0
  31. package/dist/core/refund-service.d.ts +39 -0
  32. package/dist/core/refund-service.js +384 -0
  33. package/dist/core/sqlite-bridge.d.ts +23 -0
  34. package/dist/core/sqlite-bridge.js +207 -0
  35. package/dist/core/storage-bridge.d.ts +18 -0
  36. package/dist/core/storage-bridge.js +99 -0
  37. package/dist/core/token-parser.d.ts +35 -0
  38. package/dist/core/token-parser.js +106 -0
  39. package/dist/core/update-checker.d.ts +62 -0
  40. package/dist/core/update-checker.js +231 -0
  41. package/dist/index.d.ts +17 -0
  42. package/dist/index.js +17 -0
  43. package/dist/menu.d.ts +12 -0
  44. package/dist/menu.js +2201 -0
  45. package/dist/types.d.ts +60 -0
  46. package/dist/types.js +5 -0
  47. package/dist/utils/browser-utils.d.ts +31 -0
  48. package/dist/utils/browser-utils.js +283 -0
  49. package/dist/utils/clipboard.d.ts +5 -0
  50. package/dist/utils/clipboard.js +48 -0
  51. package/dist/utils/live-menu.d.ts +26 -0
  52. package/dist/utils/live-menu.js +169 -0
  53. package/dist/utils/plan-formatter.d.ts +30 -0
  54. package/dist/utils/plan-formatter.js +153 -0
  55. package/dist/utils/prompt-utils.d.ts +40 -0
  56. package/dist/utils/prompt-utils.js +105 -0
  57. package/dist/utils/security.d.ts +6 -0
  58. package/dist/utils/security.js +27 -0
  59. package/dist/utils/table-renderer.d.ts +7 -0
  60. package/dist/utils/table-renderer.js +88 -0
  61. package/dist/utils/time-formatter.d.ts +13 -0
  62. package/dist/utils/time-formatter.js +83 -0
  63. package/package.json +53 -0
@@ -0,0 +1,671 @@
1
+ /**
2
+ * Outlook / 微软邮箱独立浏览器实例自动登录与安全交接引擎
3
+ * 支持 Windows / macOS / Linux / WSL 全平台多浏览器 (Chrome / Edge / Brave / Chromium)
4
+ * 采用 Detached 独立进程常驻 + 原生零依赖 CDP 会话控制
5
+ * 遇到辅助邮箱验证、两步验证、安全代码、密码错误时自动优雅停下交接给用户
6
+ */
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import fs from 'node:fs';
10
+ import { spawn } from 'node:child_process';
11
+ import chalk from 'chalk';
12
+ import boxen from 'boxen';
13
+ import { CdpEngine } from './cdp-engine.js';
14
+ import { findInstalledBrowsers, openBrowserUrl } from '../utils/browser-utils.js';
15
+ import { copyToClipboard } from '../utils/clipboard.js';
16
+ export class OutlookLauncher {
17
+ /**
18
+ * 生成专属隔离的 Outlook 浏览器 Profile 目录
19
+ * 使得同一个邮箱的 Cookie 与登录态长期有效,下一次打开直接秒进收件箱
20
+ */
21
+ static getOutlookProfileDir(email) {
22
+ const safeName = email
23
+ .trim()
24
+ .toLowerCase()
25
+ .replace(/[^a-z0-9._-]/g, '_')
26
+ .replace(/^_+|_+$/g, '');
27
+ const baseDir = process.platform === 'win32'
28
+ ? process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local')
29
+ : os.homedir();
30
+ const profileDir = path.join(baseDir, '.cursor-switch', 'outlook-profiles', safeName || 'default');
31
+ if (!fs.existsSync(profileDir)) {
32
+ fs.mkdirSync(profileDir, { recursive: true });
33
+ }
34
+ return profileDir;
35
+ }
36
+ /**
37
+ * 构造微软官方带预填参数的直接登录 URL
38
+ * 传入 login_hint 与 username 可跳过微软官网首页引导,直达该账号的密码验证页
39
+ */
40
+ static getOutlookLoginUrl(email) {
41
+ const trimmed = email.trim();
42
+ const domain = trimmed.includes('@') ? trimmed.split('@')[1].toLowerCase() : 'outlook.com';
43
+ const params = new URLSearchParams({
44
+ wa: 'wsignin1.0',
45
+ wp: 'MBI_SSL',
46
+ wreply: 'https://outlook.live.com/owa/?nlp=1',
47
+ id: '292841',
48
+ aadredir: '1',
49
+ CBCXT: 'out',
50
+ lw: '1',
51
+ fl: 'dob,flname,wld',
52
+ cobrandid: '90015',
53
+ whr: domain,
54
+ login_hint: trimmed,
55
+ username: trimmed,
56
+ });
57
+ return `https://login.live.com/login.srf?${params.toString()}`;
58
+ }
59
+ /**
60
+ * 调起全新独立浏览器实例并执行 Outlook 自动化登录
61
+ */
62
+ static async openMailbox(options) {
63
+ const email = options.email.trim();
64
+ const password = (options.emailPassword || '').trim();
65
+ const profileDir = this.getOutlookProfileDir(email);
66
+ const loginUrl = this.getOutlookLoginUrl(email);
67
+ // 1. 寻找本地可用的 Chromium 内核浏览器 (Chrome / Edge / Brave 等)
68
+ const installed = findInstalledBrowsers();
69
+ const chrome = installed.find((b) => b.name.includes('Chrome'));
70
+ const edge = installed.find((b) => b.name.includes('Edge'));
71
+ const brave = installed.find((b) => b.name.includes('Brave'));
72
+ const anyChromium = installed.find((b) => b.name.includes('Chromium') ||
73
+ b.path.toLowerCase().endsWith('chrome.exe') ||
74
+ b.path.toLowerCase().endsWith('msedge.exe'));
75
+ const selectedBrowser = chrome || edge || brave || anyChromium || installed[0];
76
+ // 若本地未检测到任何 Chromium 内核浏览器,执行优雅降级
77
+ if (!selectedBrowser || !fs.existsSync(selectedBrowser.path)) {
78
+ if (password) {
79
+ await copyToClipboard(password);
80
+ }
81
+ await openBrowserUrl(loginUrl);
82
+ return {
83
+ success: false,
84
+ email,
85
+ status: 'no_browser',
86
+ profileDir,
87
+ message: '未探测到系统 Chrome/Edge 浏览器,已降级在默认浏览器中打开,密码已复制到剪贴板。',
88
+ };
89
+ }
90
+ // 2. 动态分配随机可用本地 CDP 端口
91
+ let cdpPort;
92
+ try {
93
+ cdpPort = await CdpEngine.getFreePort();
94
+ }
95
+ catch {
96
+ cdpPort = 9222;
97
+ }
98
+ // 3. 构建 Detached 启动参数,确保浏览器即使 CLI 退出后依然独立常驻
99
+ const launchArgs = [
100
+ `--user-data-dir=${profileDir}`,
101
+ `--remote-debugging-port=${cdpPort}`,
102
+ '--remote-debugging-address=127.0.0.1',
103
+ '--remote-allow-origins=*',
104
+ '--new-window',
105
+ '--no-first-run',
106
+ '--no-default-browser-check',
107
+ loginUrl,
108
+ ];
109
+ try {
110
+ const child = spawn(selectedBrowser.path, launchArgs, {
111
+ detached: true,
112
+ stdio: 'ignore',
113
+ windowsHide: false,
114
+ });
115
+ child.unref();
116
+ }
117
+ catch (err) {
118
+ return {
119
+ success: false,
120
+ email,
121
+ status: 'error',
122
+ profileDir,
123
+ message: `调起浏览器失败: ${err.message || String(err)}`,
124
+ };
125
+ }
126
+ // 4. 等待 CDP 端口就绪并连接
127
+ const target = await CdpEngine.waitForPageTarget(cdpPort, 15000);
128
+ if (!target || !target.webSocketDebuggerUrl) {
129
+ // 浏览器已打开,但 CDP 端口未在限定时间内响应(可能是已复用了旧实例)
130
+ return {
131
+ success: true,
132
+ email,
133
+ status: 'manual_required',
134
+ profileDir,
135
+ message: '已成功调起独立浏览器窗口,请在打开的页面中继续操作。',
136
+ };
137
+ }
138
+ const cdp = new CdpEngine(target.webSocketDebuggerUrl);
139
+ try {
140
+ await cdp.connect(10000);
141
+ await cdp.send('Page.enable');
142
+ await cdp.send('Runtime.enable');
143
+ // 若指定了同时打开 Cursor Dashboard,则预先注入 Token Cookie 并新建标签页直达后台
144
+ if (options.openDashboard && options.cursorToken) {
145
+ try {
146
+ await cdp.send('Network.enable');
147
+ await cdp.send('Network.setCookie', {
148
+ name: 'WorkosCursorSessionToken',
149
+ value: options.cursorToken.trim().replace(/["\r\n]/g, ''),
150
+ domain: '.cursor.com',
151
+ path: '/',
152
+ secure: true,
153
+ httpOnly: false,
154
+ sameSite: 'Lax',
155
+ expires: Math.floor(Date.now() / 1000) + 365 * 86400,
156
+ });
157
+ await cdp.send('Network.setCookie', {
158
+ name: 'NEXT_LOCALE',
159
+ value: 'zh-CN',
160
+ domain: '.cursor.com',
161
+ path: '/',
162
+ expires: Math.floor(Date.now() / 1000) + 365 * 86400,
163
+ });
164
+ await cdp.send('Target.createTarget', { url: 'https://cursor.com/cn/dashboard' });
165
+ console.log(chalk.green(' → 已在当前浏览器新标签页中免密开启 Cursor Dashboard 控制台!'));
166
+ }
167
+ catch { }
168
+ }
169
+ }
170
+ catch {
171
+ return {
172
+ success: true,
173
+ email,
174
+ status: 'manual_required',
175
+ profileDir,
176
+ message: '浏览器已成功调起,请在窗口中操作。',
177
+ };
178
+ }
179
+ // 5. 自动化登录探测状态机
180
+ let emailFilled = false;
181
+ let passwordFilled = false;
182
+ let passwordSubmittedAt = 0;
183
+ let usePasswordAttempts = 0;
184
+ let securityProofDetectedCount = 0;
185
+ const deadline = Date.now() + 60000; // 最长观察 60 秒
186
+ const securityBlockerMarkers = [
187
+ 'help us protect your account',
188
+ 'verify your identity',
189
+ 'add another way to verify your identity',
190
+ 'enter code',
191
+ 'approve sign in request',
192
+ 'two-step',
193
+ 'authenticator',
194
+ '让我们来保护你的帐户',
195
+ '让我们来保护你的账户',
196
+ '添加另一种方法来验证你的身份',
197
+ '帮助我们保护你的帐户',
198
+ '帮助我们保护你的账户',
199
+ '验证你的身份',
200
+ '输入代码',
201
+ '验证器',
202
+ '发送电子邮件',
203
+ '发送代码',
204
+ '备用电子邮件',
205
+ '备用邮箱',
206
+ '验证你的电子邮件',
207
+ ];
208
+ const wrongPasswordMarkers = [
209
+ '此密码不是你的',
210
+ '此密码不正确',
211
+ '密码不正确',
212
+ 'incorrect password',
213
+ 'account or password is incorrect',
214
+ "that microsoft account doesn't exist",
215
+ '帐户或密码不正确',
216
+ '账户或密码不正确',
217
+ ];
218
+ try {
219
+ while (Date.now() < deadline) {
220
+ const curUrl = (await cdp.getCurrentUrl()).toLowerCase();
221
+ const bodyText = await cdp.getBodyText();
222
+ const bodyLower = bodyText.toLowerCase();
223
+ // 状态 1: 已成功进入 Outlook 收件箱
224
+ if (curUrl.includes('outlook.live.com/mail') ||
225
+ curUrl.includes('outlook.office.com/mail') ||
226
+ curUrl.includes('outlook.office365.com/mail')) {
227
+ let otpCode = undefined;
228
+ if (options.sniffOtp) {
229
+ const found = await this.sniffVerificationCode(cdp, options.sniffTimeoutMs || 20000);
230
+ if (found) {
231
+ otpCode = found;
232
+ }
233
+ }
234
+ await cdp.bringToFront();
235
+ cdp.disconnect();
236
+ return {
237
+ success: true,
238
+ email,
239
+ status: 'logged_in',
240
+ profileDir,
241
+ otpCode,
242
+ message: otpCode
243
+ ? `Outlook 邮箱已成功登录并自动捕获验证码 [${otpCode}]!`
244
+ : 'Outlook 邮箱已成功登录并进入收件箱!',
245
+ };
246
+ }
247
+ // 状态 2: 密码错误检测(仅在本次尝试提交过密码后才检测,防止旧错误文本误判)
248
+ if (passwordFilled && passwordSubmittedAt > 0 && Date.now() - passwordSubmittedAt > 800) {
249
+ if (wrongPasswordMarkers.some((m) => bodyLower.includes(m))) {
250
+ await cdp.bringToFront();
251
+ cdp.disconnect();
252
+ return {
253
+ success: false,
254
+ email,
255
+ status: 'wrong_password',
256
+ profileDir,
257
+ message: '邮箱密码不正确,已停止自动重试;请在已打开的浏览器中核对输入。',
258
+ };
259
+ }
260
+ }
261
+ // 状态 3: 检查密码输入框是否已出现 (优先处理密码输入,兼容 position: fixed 弹窗)
262
+ const hasPwdInput = await cdp.evaluate(`(() => {
263
+ const el = document.querySelector('input[name="passwd"], #i0118, #passwordEntry, input[type="password"]');
264
+ if (!el || el.disabled) return false;
265
+ const style = window.getComputedStyle(el);
266
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
267
+ const r = el.getBoundingClientRect();
268
+ return (r.width > 0 && r.height > 0) || el.getClientRects().length > 0;
269
+ })()`);
270
+ if (hasPwdInput && !passwordFilled) {
271
+ if (password) {
272
+ console.log(chalk.cyan(' → 检测到密码输入框,正在填入密码并提交...'));
273
+ const filled = await cdp.fillInput('input[name="passwd"], #i0118, #passwordEntry, input[type="password"]', password);
274
+ if (filled) {
275
+ await new Promise((r) => setTimeout(r, 400));
276
+ await cdp.click('#idSIButton9, button[data-testid="primaryButton"], button[type="submit"], input[type="submit"]');
277
+ passwordFilled = true;
278
+ passwordSubmittedAt = Date.now();
279
+ securityProofDetectedCount = 0;
280
+ await new Promise((r) => setTimeout(r, 1500));
281
+ continue;
282
+ }
283
+ }
284
+ else {
285
+ // 没有密码,置顶页面提示用户手工录入密码
286
+ await cdp.bringToFront();
287
+ cdp.disconnect();
288
+ return {
289
+ success: true,
290
+ email,
291
+ status: 'manual_password',
292
+ profileDir,
293
+ message: '已自动填入邮箱并定位到密码输入框,未配置密码,请在浏览器中直接输入密码。',
294
+ };
295
+ }
296
+ }
297
+ // 状态 4: 处理登录账号输入 (过滤掉辅助邮箱验证输入框)
298
+ if (!emailFilled) {
299
+ const hasLoginInput = await cdp.evaluate(`(() => {
300
+ const el = document.querySelector('input[name="loginfmt"], #i0116, input[type="email"]:not([id*="proof"])');
301
+ if (!el || el.disabled) return false;
302
+ const style = window.getComputedStyle(el);
303
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
304
+ const r = el.getBoundingClientRect();
305
+ return (r.width > 0 && r.height > 0) || el.getClientRects().length > 0;
306
+ })()`);
307
+ if (hasLoginInput) {
308
+ console.log(chalk.cyan(' → 检测到邮箱账号输入框,正在填入账号...'));
309
+ const filled = await cdp.fillInput('input[name="loginfmt"], #i0116, input[type="email"]:not([id*="proof"])', email);
310
+ if (filled) {
311
+ await new Promise((r) => setTimeout(r, 300));
312
+ await cdp.click('#idSIButton9, button[data-testid="primaryButton"], button[type="submit"], input[type="submit"]');
313
+ emailFilled = true;
314
+ await new Promise((r) => setTimeout(r, 1200));
315
+ continue;
316
+ }
317
+ }
318
+ }
319
+ // 状态 5:【核心机制】优先寻找“使用密码 / 改用密码 / 密码登录 / Use your password”入口!
320
+ // 微软在引导验证辅助邮箱、通行密钥或二次验证时,常在底部提供“使用密码”备选项
321
+ if (!passwordFilled && usePasswordAttempts < 6) {
322
+ const clickedSwitch = await this.tryClickUsePassword(cdp);
323
+ if (clickedSwitch) {
324
+ console.log(chalk.cyan(' → 检测到页面提供“使用密码”入口,已自动点击切换到密码登录...'));
325
+ usePasswordAttempts++;
326
+ securityProofDetectedCount = 0;
327
+ await new Promise((r) => setTimeout(r, 1800));
328
+ continue;
329
+ }
330
+ }
331
+ // 状态 6: 保持登录状态 (KMSI - Keep Me Signed In) 页面 -> 自动点击“是”
332
+ const isKmsi = await cdp.evaluate(`(() => {
333
+ const text = (document.body && document.body.innerText || '').toLowerCase();
334
+ return text.includes('保持登录状态') || text.includes('stay signed in') || text.includes('stay sign in');
335
+ })()`);
336
+ if (isKmsi) {
337
+ console.log(chalk.cyan(' → 检测到“保持登录状态”引导,正在自动选择“是”...'));
338
+ const clicked = await cdp.click('#idSIButton9, button[data-testid="primaryButton"], input[value="是"], input[value="Yes"]');
339
+ if (clicked) {
340
+ await new Promise((r) => setTimeout(r, 1500));
341
+ continue;
342
+ }
343
+ }
344
+ // 状态 6.5: 微软服务协议与条款更新 (TOU - Terms of Use) 确认页 -> 自动点击“下一步” / “接受”
345
+ const isTou = curUrl.includes('/tou/') ||
346
+ curUrl.includes('/tou') ||
347
+ bodyLower.includes('更新条款') ||
348
+ bodyLower.includes('即将更新条款') ||
349
+ bodyLower.includes('服务协议') ||
350
+ bodyLower.includes('terms of use');
351
+ if (isTou) {
352
+ console.log(chalk.cyan(' → 检测到微软条款更新确认页,正在自动点击“下一步”...'));
353
+ const clicked = await cdp.click('#idSIButton9, button[data-testid="primaryButton"], button[type="submit"], input[type="submit"], #iNext');
354
+ if (clicked) {
355
+ await new Promise((r) => setTimeout(r, 2000));
356
+ continue;
357
+ }
358
+ }
359
+ // 状态 7: 辅助邮箱 / 安全验证 / MFA 敏感阻断检测
360
+ // 关键逻辑:只有在【确认无法切换为密码登录】(页面无“使用密码”按钮,或已提交密码后要求验证码)时,才停下交接给用户!
361
+ const isSecurityProofUrl = curUrl.includes('/proofs/add') || curUrl.includes('/proofs/manage') || curUrl.includes('/proofs');
362
+ const hasSecurityMarker = securityBlockerMarkers.some((m) => bodyLower.includes(m));
363
+ const hasMaskedEmail = /[a-z0-9._%+-]*\*{3,}@[a-z0-9.-]+/i.test(bodyText);
364
+ if (isSecurityProofUrl || (hasSecurityMarker && (hasMaskedEmail || curUrl.includes('login.live.com')))) {
365
+ if (!passwordFilled) {
366
+ // 再次扫描页面是否存在“使用密码”入口
367
+ const canSwitch = await this.tryClickUsePassword(cdp);
368
+ if (canSwitch && usePasswordAttempts < 6) {
369
+ usePasswordAttempts++;
370
+ securityProofDetectedCount = 0;
371
+ await new Promise((r) => setTimeout(r, 1500));
372
+ continue;
373
+ }
374
+ // 给予 3 次缓冲探测机会(约 3 秒),等待前端页面渲染出“使用密码”
375
+ securityProofDetectedCount++;
376
+ if (securityProofDetectedCount < 3) {
377
+ await new Promise((r) => setTimeout(r, 1000));
378
+ continue;
379
+ }
380
+ }
381
+ // 确认实在没有密码登录方式,或者是密码提交后强制要求的辅助邮箱验证码,才真正停下交接
382
+ await cdp.bringToFront();
383
+ cdp.disconnect();
384
+ return {
385
+ success: true,
386
+ email,
387
+ status: 'manual_required',
388
+ profileDir,
389
+ message: '微软要求安全验证 (辅助邮箱验证码/两步验证/补充信息),当前页面无可用密码通道,已为您置顶浏览器窗口,请手动完成验证。',
390
+ };
391
+ }
392
+ // 状态 8: 官网营销页误跳转处理
393
+ if (curUrl.includes('microsoft.com') && curUrl.includes('outlook')) {
394
+ const clicked = await cdp.click("a[href*='login.live.com'], a[href*='outlook.live.com']");
395
+ if (clicked) {
396
+ await new Promise((r) => setTimeout(r, 1500));
397
+ continue;
398
+ }
399
+ }
400
+ await new Promise((r) => setTimeout(r, 700));
401
+ }
402
+ // 超时返回
403
+ await cdp.bringToFront();
404
+ cdp.disconnect();
405
+ return {
406
+ success: true,
407
+ email,
408
+ status: 'timeout',
409
+ profileDir,
410
+ message: '自动化登录等待已超时,浏览器已为您保持打开,请在窗口中继续。',
411
+ };
412
+ }
413
+ catch (err) {
414
+ cdp.disconnect();
415
+ const msg = err?.message || String(err);
416
+ const isClosed = msg.includes('关闭') || msg.includes('closed') || msg.includes('ECONNREFUSED') || msg.includes('reset');
417
+ return {
418
+ success: false,
419
+ email,
420
+ status: 'error',
421
+ profileDir,
422
+ message: isClosed ? '浏览器窗口已关闭,自动化流程已退出。' : `自动化控制异常: ${msg}`,
423
+ };
424
+ }
425
+ }
426
+ /**
427
+ * 优先尝试点击页面上的“使用密码 / 改用密码 / 密码登录 / Use your password / 使用其他方式”入口
428
+ * 采用原生 CDP 屏幕坐标模拟真实用户点击,彻底击穿各类前端框架 (Fluent UI / React) 遮挡与事件委托限制
429
+ */
430
+ static async tryClickUsePassword(cdp) {
431
+ try {
432
+ const point = await cdp.evaluate(`(() => {
433
+ // 1. 若存在半透明全屏加载蒙层,临时穿透,避免遮挡正常可点击元素
434
+ const loaders = document.querySelectorAll('div[aria-label*="加载"], div[aria-label*="loading"]');
435
+ loaders.forEach(l => {
436
+ if (l instanceof HTMLElement) {
437
+ l.style.pointerEvents = 'none';
438
+ }
439
+ });
440
+
441
+ const isVisible = (el) => {
442
+ if (!el || el.disabled) return false;
443
+ const rect = el.getBoundingClientRect();
444
+ const style = window.getComputedStyle(el);
445
+ return rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none';
446
+ };
447
+
448
+ // 2. 微软官方固定 ID / 属性选择器
449
+ const idSelectors = [
450
+ '#idA_PWD_SwitchToPassword',
451
+ '#idA_IL_SwitchToPassword',
452
+ '#signInAnotherWay',
453
+ '#idA_PWD_SwitchToCredPicker',
454
+ 'a[role="button"][id*="SwitchToPassword"]',
455
+ 'button[id*="SwitchToPassword"]',
456
+ 'a[id*="SwitchToPassword"]',
457
+ 'a[id*="switchToPassword"]',
458
+ 'a[id*="switch"]',
459
+ 'span[role="button"].fui-Link',
460
+ 'button.fui-Link',
461
+ 'a.fui-Link',
462
+ ];
463
+
464
+ for (const sel of idSelectors) {
465
+ const matches = Array.from(document.querySelectorAll(sel));
466
+ for (const el of matches) {
467
+ if (isVisible(el)) {
468
+ const text = (el.innerText || el.textContent || '').trim().toLowerCase();
469
+ if (!text || text.includes('密码') || text.includes('password') || text.includes('方式') || text.includes('another way')) {
470
+ el.scrollIntoView({ block: 'center' });
471
+ const r = el.getBoundingClientRect();
472
+ return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
473
+ }
474
+ }
475
+ }
476
+ }
477
+
478
+ // 3. 关键词扫描 - 重点:优先匹配具备交互特征的具体子元素 (role="button", button, a, span.fui-Link)
479
+ const markers = [
480
+ '使用密码',
481
+ '改用密码',
482
+ '密码登录',
483
+ '输入你的密码',
484
+ '使用你的密码',
485
+ '使用另一种方式登录',
486
+ '使用其他方式登录',
487
+ '其他登录方式',
488
+ '通过其他方式登录',
489
+ 'use your password',
490
+ 'use password',
491
+ 'use your password instead',
492
+ 'sign in with password',
493
+ 'sign in with your password',
494
+ 'sign in another way',
495
+ 'other ways to sign in',
496
+ ];
497
+
498
+ const interactiveNodes = Array.from(document.querySelectorAll('[role="button"], button, a, span.fui-Link, div[role="button"]'));
499
+ for (const el of interactiveNodes) {
500
+ if (!isVisible(el)) continue;
501
+ const text = (el.innerText || el.textContent || el.getAttribute('aria-label') || '').trim().replace(/\\s+/g, ' ').toLowerCase();
502
+ for (const m of markers) {
503
+ if (text === m || (text.includes(m) && text.length <= m.length + 10)) {
504
+ el.scrollIntoView({ block: 'center' });
505
+ const r = el.getBoundingClientRect();
506
+ return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
507
+ }
508
+ }
509
+ }
510
+
511
+ // 4. 全局模糊扫描节点并向下/向上定位具体可点击项
512
+ const allNodes = Array.from(document.querySelectorAll('span, div, p, a, button'));
513
+ for (const node of allNodes) {
514
+ if (!isVisible(node)) continue;
515
+ const rawText = (node.innerText || node.textContent || '').trim();
516
+ const text = rawText.replace(/\\s+/g, ' ').toLowerCase();
517
+ if (!text || text.length > 40) continue;
518
+ for (const m of markers) {
519
+ if (text === m || (text.includes(m) && text.length <= m.length + 8)) {
520
+ const innerAction = node.querySelector('[role="button"], a, button, .fui-Link');
521
+ const target = innerAction || node.closest('[role="button"], button, a, [tabindex]') || node;
522
+ target.scrollIntoView({ block: 'center' });
523
+ const r = target.getBoundingClientRect();
524
+ return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
525
+ }
526
+ }
527
+ }
528
+
529
+ // 5. 凭据选择器列表 (Credential Picker)
530
+ const tiles = Array.from(document.querySelectorAll('.table, .row, [role="button"], .tile, #credentialList [role="button"]'));
531
+ for (const tile of tiles) {
532
+ if (!isVisible(tile)) continue;
533
+ const text = (tile.innerText || tile.textContent || '').trim().toLowerCase();
534
+ if (text.includes('密码') || text.includes('password')) {
535
+ tile.scrollIntoView({ block: 'center' });
536
+ const r = tile.getBoundingClientRect();
537
+ return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
538
+ }
539
+ }
540
+
541
+ return null;
542
+ })()`);
543
+ if (point && typeof point.x === 'number' && typeof point.y === 'number') {
544
+ // 使用原生 CDP 鼠标事件模拟真实用户物理点击
545
+ await cdp.clickPoint(point.x, point.y);
546
+ return true;
547
+ }
548
+ return false;
549
+ }
550
+ catch {
551
+ return false;
552
+ }
553
+ }
554
+ /**
555
+ * 格式化打印操作结果卡片
556
+ */
557
+ static printResultCard(result) {
558
+ if (result.status === 'logged_in') {
559
+ console.log(boxen([
560
+ chalk.bold.green('✔ Outlook 邮箱已成功进入收件箱'),
561
+ chalk.dim('────────────────────────────────────────────────────────────'),
562
+ ` 登录邮箱 : ${chalk.bold.white(result.email)}`,
563
+ ` 隔离数据 : ${chalk.grey(result.profileDir || '--')}`,
564
+ ` 运行状态 : ${chalk.green('● 浏览器常驻中')} ${chalk.dim('(独立隔离实例,不影响日常 Cookie)')}`,
565
+ ].join('\n'), {
566
+ padding: { top: 0, bottom: 0, left: 1, right: 1 },
567
+ borderColor: 'green',
568
+ borderStyle: 'round',
569
+ }));
570
+ }
571
+ else if (result.status === 'manual_required') {
572
+ console.log(boxen([
573
+ chalk.bold.yellow('⚠️ 微软要求安全验证 / 辅助邮箱'),
574
+ chalk.dim('────────────────────────────────────────────────────────────'),
575
+ ` 目标邮箱 : ${chalk.bold.white(result.email)}`,
576
+ ` 安全状态 : ${chalk.yellow('检测到安全验证')} ${chalk.dim('(辅助邮箱取码 / 两步验证 / 补充信息)')}`,
577
+ '',
578
+ chalk.white('💡【操作指引】:'),
579
+ chalk.cyan('已为您自动停止自动脚本,并将独立浏览器窗口置顶在屏幕最前!'),
580
+ chalk.grey('请在打开的网页中手动完成辅助邮箱或验证码输入,窗口将保持常驻。'),
581
+ ].join('\n'), {
582
+ padding: { top: 0, bottom: 0, left: 1, right: 1 },
583
+ borderColor: 'yellow',
584
+ borderStyle: 'round',
585
+ }));
586
+ }
587
+ else if (result.status === 'wrong_password') {
588
+ console.log(boxen([
589
+ chalk.bold.red('✖ 微软邮箱密码错误'),
590
+ chalk.dim('────────────────────────────────────────────────────────────'),
591
+ ` 目标邮箱 : ${chalk.bold.white(result.email)}`,
592
+ ` 错误提示 : ${chalk.red(result.message)}`,
593
+ chalk.dim('────────────────────────────────────────────────────────────'),
594
+ chalk.yellow('为防止触发微软账号安全风控封锁,自动化已立即终止,请核对密码。'),
595
+ ].join('\n'), {
596
+ padding: { top: 0, bottom: 0, left: 1, right: 1 },
597
+ borderColor: 'red',
598
+ borderStyle: 'round',
599
+ }));
600
+ }
601
+ else {
602
+ console.log(boxen([
603
+ chalk.bold.cyan('🌐 Outlook 独立浏览器已开启'),
604
+ chalk.dim('────────────────────────────────────────────────────────────'),
605
+ ` 登录邮箱 : ${chalk.bold.white(result.email)}`,
606
+ ` 提示说明 : ${chalk.white(result.message)}`,
607
+ ].join('\n'), {
608
+ padding: { top: 0, bottom: 0, left: 1, right: 1 },
609
+ borderColor: 'cyan',
610
+ borderStyle: 'round',
611
+ }));
612
+ }
613
+ }
614
+ /**
615
+ * 在已到达 Outlook 收件箱页面时,利用 CDP 实时嗅探 Cursor / WorkOS 最新的 6 位数字验证码
616
+ */
617
+ static async sniffVerificationCode(cdp, timeoutMs = 20000) {
618
+ const end = Date.now() + timeoutMs;
619
+ console.log(chalk.cyan(' → 浏览器已成功进入收件箱,正在实时探测 Cursor 邮件验证码...'));
620
+ // 等待 1.5 秒让 Outlook 单页应用渲染出邮件列表
621
+ await new Promise((r) => setTimeout(r, 1500));
622
+ while (Date.now() < end) {
623
+ try {
624
+ const found = await cdp.evaluate(`(() => {
625
+ // 1. 尝试在邮件列表项中查找来自 Cursor / WorkOS 的邮件项
626
+ const listItems = Array.from(document.querySelectorAll('div[role="option"], div[data-convid], div[aria-label*="Cursor"], div[aria-label*="WorkOS"]'));
627
+ for (const item of listItems) {
628
+ const label = ((item.getAttribute('aria-label') || '') + ' ' + (item.innerText || '')).trim();
629
+ if (/cursor|workos/i.test(label)) {
630
+ // 邮件标题或预览中若直接包含 6 位数字
631
+ const m = label.match(/\\b(\\d{6})\\b/);
632
+ if (m) return m[1];
633
+ // 尝试点选该邮件展开阅读窗格
634
+ try { (item as HTMLElement).click(); } catch {}
635
+ break;
636
+ }
637
+ }
638
+
639
+ // 2. 检查正文或阅读窗格中是否有 6 位验证码
640
+ const bodyText = document.body ? document.body.innerText : '';
641
+ const matchContext = bodyText.match(/(?:cursor|workos|verification code|one-time code|代码|验证码)[\\s\\S]{0,80}?\\b(\\d{6})\\b/i);
642
+ if (matchContext && matchContext[1]) {
643
+ return matchContext[1];
644
+ }
645
+
646
+ // 3. 检查常规阅读窗格内的 6 位数字
647
+ const readingPane = document.querySelector('div[role="region"][aria-label*="Reading"], div[data-app-section="ConversationReadingPane"], div[aria-label*="邮件内容"], #Item\\.MessageUniqueBody');
648
+ if (readingPane) {
649
+ const m = (readingPane as HTMLElement).innerText.match(/\\b(\\d{6})\\b/);
650
+ if (m) return m[1];
651
+ }
652
+
653
+ // 4. 若第一封邮件就是 Cursor 发送的
654
+ const firstMail = document.querySelector('div[role="option"]');
655
+ if (firstMail) {
656
+ const m = (firstMail as HTMLElement).innerText.match(/\\b(\\d{6})\\b/);
657
+ if (m) return m[1];
658
+ }
659
+
660
+ return null;
661
+ })()`);
662
+ if (found && /^\d{6}$/.test(found)) {
663
+ return found;
664
+ }
665
+ }
666
+ catch { }
667
+ await new Promise((r) => setTimeout(r, 1500));
668
+ }
669
+ return null;
670
+ }
671
+ }