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,9 +1,3 @@
1
- /**
2
- * Outlook / 微软邮箱独立浏览器实例自动登录与安全交接引擎
3
- * 支持 Windows / macOS / Linux / WSL 全平台多浏览器 (Chrome / Edge / Brave / Chromium)
4
- * 采用 Detached 独立进程常驻 + 原生零依赖 CDP 会话控制
5
- * 遇到辅助邮箱验证、两步验证、安全代码、密码错误时自动优雅停下交接给用户
6
- */
7
1
  import os from 'node:os';
8
2
  import path from 'node:path';
9
3
  import fs from 'node:fs';
@@ -14,10 +8,6 @@ import { CdpEngine } from './cdp-engine.js';
14
8
  import { findInstalledBrowsers, openBrowserUrl } from '../utils/browser-utils.js';
15
9
  import { copyToClipboard } from '../utils/clipboard.js';
16
10
  export class OutlookLauncher {
17
- /**
18
- * 生成专属隔离的 Outlook 浏览器 Profile 目录
19
- * 使得同一个邮箱的 Cookie 与登录态长期有效,下一次打开直接秒进收件箱
20
- */
21
11
  static getOutlookProfileDir(email) {
22
12
  const safeName = email
23
13
  .trim()
@@ -33,10 +23,6 @@ export class OutlookLauncher {
33
23
  }
34
24
  return profileDir;
35
25
  }
36
- /**
37
- * 构造微软官方带预填参数的直接登录 URL
38
- * 传入 login_hint 与 username 可跳过微软官网首页引导,直达该账号的密码验证页
39
- */
40
26
  static getOutlookLoginUrl(email) {
41
27
  const trimmed = email.trim();
42
28
  const domain = trimmed.includes('@') ? trimmed.split('@')[1].toLowerCase() : 'outlook.com';
@@ -56,15 +42,11 @@ export class OutlookLauncher {
56
42
  });
57
43
  return `https://login.live.com/login.srf?${params.toString()}`;
58
44
  }
59
- /**
60
- * 调起全新独立浏览器实例并执行 Outlook 自动化登录
61
- */
62
45
  static async openMailbox(options) {
63
46
  const email = options.email.trim();
64
47
  const password = (options.emailPassword || '').trim();
65
48
  const profileDir = this.getOutlookProfileDir(email);
66
49
  const loginUrl = this.getOutlookLoginUrl(email);
67
- // 1. 寻找本地可用的 Chromium 内核浏览器 (Chrome / Edge / Brave 等)
68
50
  const installed = findInstalledBrowsers();
69
51
  const chrome = installed.find((b) => b.name.includes('Chrome'));
70
52
  const edge = installed.find((b) => b.name.includes('Edge'));
@@ -73,7 +55,6 @@ export class OutlookLauncher {
73
55
  b.path.toLowerCase().endsWith('chrome.exe') ||
74
56
  b.path.toLowerCase().endsWith('msedge.exe'));
75
57
  const selectedBrowser = chrome || edge || brave || anyChromium || installed[0];
76
- // 若本地未检测到任何 Chromium 内核浏览器,执行优雅降级
77
58
  if (!selectedBrowser || !fs.existsSync(selectedBrowser.path)) {
78
59
  if (password) {
79
60
  await copyToClipboard(password);
@@ -87,7 +68,6 @@ export class OutlookLauncher {
87
68
  message: '未探测到系统 Chrome/Edge 浏览器,已降级在默认浏览器中打开,密码已复制到剪贴板。',
88
69
  };
89
70
  }
90
- // 2. 动态分配随机可用本地 CDP 端口
91
71
  let cdpPort;
92
72
  try {
93
73
  cdpPort = await CdpEngine.getFreePort();
@@ -95,7 +75,6 @@ export class OutlookLauncher {
95
75
  catch {
96
76
  cdpPort = 9222;
97
77
  }
98
- // 3. 构建 Detached 启动参数,确保浏览器即使 CLI 退出后依然独立常驻
99
78
  const launchArgs = [
100
79
  `--user-data-dir=${profileDir}`,
101
80
  `--remote-debugging-port=${cdpPort}`,
@@ -123,10 +102,8 @@ export class OutlookLauncher {
123
102
  message: `调起浏览器失败: ${err.message || String(err)}`,
124
103
  };
125
104
  }
126
- // 4. 等待 CDP 端口就绪并连接
127
105
  const target = await CdpEngine.waitForPageTarget(cdpPort, 15000);
128
106
  if (!target || !target.webSocketDebuggerUrl) {
129
- // 浏览器已打开,但 CDP 端口未在限定时间内响应(可能是已复用了旧实例)
130
107
  return {
131
108
  success: true,
132
109
  email,
@@ -140,7 +117,6 @@ export class OutlookLauncher {
140
117
  await cdp.connect(10000);
141
118
  await cdp.send('Page.enable');
142
119
  await cdp.send('Runtime.enable');
143
- // 若指定了同时打开 Cursor Dashboard,则预先注入 Token Cookie 并新建标签页直达后台
144
120
  if (options.openDashboard && options.cursorToken) {
145
121
  try {
146
122
  await cdp.send('Network.enable');
@@ -176,13 +152,12 @@ export class OutlookLauncher {
176
152
  message: '浏览器已成功调起,请在窗口中操作。',
177
153
  };
178
154
  }
179
- // 5. 自动化登录探测状态机
180
155
  let emailFilled = false;
181
156
  let passwordFilled = false;
182
157
  let passwordSubmittedAt = 0;
183
158
  let usePasswordAttempts = 0;
184
159
  let securityProofDetectedCount = 0;
185
- const deadline = Date.now() + 60000; // 最长观察 60 秒
160
+ const deadline = Date.now() + 60000;
186
161
  const securityBlockerMarkers = [
187
162
  'help us protect your account',
188
163
  'verify your identity',
@@ -220,7 +195,6 @@ export class OutlookLauncher {
220
195
  const curUrl = (await cdp.getCurrentUrl()).toLowerCase();
221
196
  const bodyText = await cdp.getBodyText();
222
197
  const bodyLower = bodyText.toLowerCase();
223
- // 状态 1: 已成功进入 Outlook 收件箱
224
198
  if (curUrl.includes('outlook.live.com/mail') ||
225
199
  curUrl.includes('outlook.office.com/mail') ||
226
200
  curUrl.includes('outlook.office365.com/mail')) {
@@ -244,7 +218,6 @@ export class OutlookLauncher {
244
218
  : 'Outlook 邮箱已成功登录并进入收件箱!',
245
219
  };
246
220
  }
247
- // 状态 2: 密码错误检测(仅在本次尝试提交过密码后才检测,防止旧错误文本误判)
248
221
  if (passwordFilled && passwordSubmittedAt > 0 && Date.now() - passwordSubmittedAt > 800) {
249
222
  if (wrongPasswordMarkers.some((m) => bodyLower.includes(m))) {
250
223
  await cdp.bringToFront();
@@ -258,14 +231,13 @@ export class OutlookLauncher {
258
231
  };
259
232
  }
260
233
  }
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;
234
+ const hasPwdInput = await cdp.evaluate(`(() => {
235
+ const el = document.querySelector('input[name="passwd"], #i0118, #passwordEntry, input[type="password"]');
236
+ if (!el || el.disabled) return false;
237
+ const style = window.getComputedStyle(el);
238
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
239
+ const r = el.getBoundingClientRect();
240
+ return (r.width > 0 && r.height > 0) || el.getClientRects().length > 0;
269
241
  })()`);
270
242
  if (hasPwdInput && !passwordFilled) {
271
243
  if (password) {
@@ -282,7 +254,6 @@ export class OutlookLauncher {
282
254
  }
283
255
  }
284
256
  else {
285
- // 没有密码,置顶页面提示用户手工录入密码
286
257
  await cdp.bringToFront();
287
258
  cdp.disconnect();
288
259
  return {
@@ -294,15 +265,14 @@ export class OutlookLauncher {
294
265
  };
295
266
  }
296
267
  }
297
- // 状态 4: 处理登录账号输入 (过滤掉辅助邮箱验证输入框)
298
268
  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;
269
+ const hasLoginInput = await cdp.evaluate(`(() => {
270
+ const el = document.querySelector('input[name="loginfmt"], #i0116, input[type="email"]:not([id*="proof"])');
271
+ if (!el || el.disabled) return false;
272
+ const style = window.getComputedStyle(el);
273
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
274
+ const r = el.getBoundingClientRect();
275
+ return (r.width > 0 && r.height > 0) || el.getClientRects().length > 0;
306
276
  })()`);
307
277
  if (hasLoginInput) {
308
278
  console.log(chalk.cyan(' → 检测到邮箱账号输入框,正在填入账号...'));
@@ -316,22 +286,35 @@ export class OutlookLauncher {
316
286
  }
317
287
  }
318
288
  }
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(' → 检测到页面提供“使用密码”入口,已自动点击切换到密码登录...'));
289
+ if (!passwordFilled && usePasswordAttempts < 2) {
290
+ const switchRes = await this.tryClickUsePassword(cdp);
291
+ if (switchRes.clicked) {
325
292
  usePasswordAttempts++;
326
- securityProofDetectedCount = 0;
327
- await new Promise((r) => setTimeout(r, 1800));
293
+ console.log(chalk.cyan(` → 检测到页面提供“${switchRes.type === 'password' ? '使用密码' : '其他登录方式'}”入口,已尝试自动点击切换 (尝试 ${usePasswordAttempts}/2)...`));
294
+ await new Promise((r) => setTimeout(r, 1200));
328
295
  continue;
329
296
  }
330
297
  }
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');
298
+ const isSecurityProofUrl = curUrl.includes('/proofs/add') || curUrl.includes('/proofs/manage') || curUrl.includes('/proofs') || curUrl.includes('login.live.com/ppsecure');
299
+ const hasSecurityMarker = securityBlockerMarkers.some((m) => bodyLower.includes(m));
300
+ const hasMaskedEmail = /[a-z0-9._%+-]*\*{3,}@[a-z0-9.-]+/i.test(bodyText);
301
+ if (isSecurityProofUrl || (hasSecurityMarker && (hasMaskedEmail || curUrl.includes('login.live.com')))) {
302
+ if (!hasPwdInput) {
303
+ console.log(chalk.yellow(' → 该账号已被微软强制要求辅助邮箱验证 (无可用直接密码通道),已置顶浏览器交接...'));
304
+ await cdp.bringToFront();
305
+ cdp.disconnect();
306
+ return {
307
+ success: true,
308
+ email,
309
+ status: 'manual_required',
310
+ profileDir,
311
+ message: '微软强制要求辅助邮箱验证,当前页面无可用直接密码通道,已为您置顶浏览器窗口,请手动完成验证。',
312
+ };
313
+ }
314
+ }
315
+ const isKmsi = await cdp.evaluate(`(() => {
316
+ const text = (document.body && document.body.innerText || '').toLowerCase();
317
+ return text.includes('保持登录状态') || text.includes('stay signed in') || text.includes('stay sign in');
335
318
  })()`);
336
319
  if (isKmsi) {
337
320
  console.log(chalk.cyan(' → 检测到“保持登录状态”引导,正在自动选择“是”...'));
@@ -341,7 +324,6 @@ export class OutlookLauncher {
341
324
  continue;
342
325
  }
343
326
  }
344
- // 状态 6.5: 微软服务协议与条款更新 (TOU - Terms of Use) 确认页 -> 自动点击“下一步” / “接受”
345
327
  const isTou = curUrl.includes('/tou/') ||
346
328
  curUrl.includes('/tou') ||
347
329
  bodyLower.includes('更新条款') ||
@@ -356,40 +338,6 @@ export class OutlookLauncher {
356
338
  continue;
357
339
  }
358
340
  }
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
341
  if (curUrl.includes('microsoft.com') && curUrl.includes('outlook')) {
394
342
  const clicked = await cdp.click("a[href*='login.live.com'], a[href*='outlook.live.com']");
395
343
  if (clicked) {
@@ -399,7 +347,6 @@ export class OutlookLauncher {
399
347
  }
400
348
  await new Promise((r) => setTimeout(r, 700));
401
349
  }
402
- // 超时返回
403
350
  await cdp.bringToFront();
404
351
  cdp.disconnect();
405
352
  return {
@@ -423,137 +370,131 @@ export class OutlookLauncher {
423
370
  };
424
371
  }
425
372
  }
426
- /**
427
- * 优先尝试点击页面上的“使用密码 / 改用密码 / 密码登录 / Use your password / 使用其他方式”入口
428
- * 采用原生 CDP 屏幕坐标模拟真实用户点击,彻底击穿各类前端框架 (Fluent UI / React) 遮挡与事件委托限制
429
- */
430
373
  static async tryClickUsePassword(cdp) {
431
374
  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;
375
+ const res = await cdp.evaluate(`(() => {
376
+ // 1. 若存在半透明全屏加载蒙层,穿透它
377
+ const loaders = document.querySelectorAll('div[aria-label*="加载"], div[aria-label*="loading"]');
378
+ loaders.forEach(l => {
379
+ if (l instanceof HTMLElement) l.style.pointerEvents = 'none';
380
+ });
381
+
382
+ const isVisible = (el) => {
383
+ if (!el || el.disabled) return false;
384
+ const rect = el.getBoundingClientRect();
385
+ const style = window.getComputedStyle(el);
386
+ return rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none';
387
+ };
388
+
389
+ const doClick = (el) => {
390
+ try {
391
+ el.scrollIntoView({ block: 'center' });
392
+ el.focus();
393
+ el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
394
+ el.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
395
+ el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
396
+ if (typeof el.click === 'function') el.click();
397
+ } catch {}
398
+ };
399
+
400
+ // 优先级 1: 查找显式“使用密码 / 密码登录”入口 (官方专有 ID 以及包含密码/password 的凭据瓷贴与按钮)
401
+ const pwdSelectors = [
402
+ '#idA_PWD_SwitchToPassword',
403
+ '#idA_IL_SwitchToPassword',
404
+ 'a[role="button"][id*="SwitchToPassword"]',
405
+ 'button[id*="SwitchToPassword"]',
406
+ 'a[id*="SwitchToPassword"]',
407
+ 'a[id*="switchToPassword"]',
408
+ '#credentialList [role="button"]',
409
+ '.tile',
410
+ ];
411
+
412
+ for (const sel of pwdSelectors) {
413
+ const matches = Array.from(document.querySelectorAll(sel));
414
+ for (const el of matches) {
415
+ if (isVisible(el)) {
416
+ const text = (el.innerText || el.textContent || el.getAttribute('aria-label') || '').trim().toLowerCase();
417
+ if (text.includes('密码') || text.includes('password') || sel.includes('Password')) {
418
+ doClick(el);
419
+ const r = el.getBoundingClientRect();
420
+ return { point: { x: r.left + r.width / 2, y: r.top + r.height / 2 }, type: 'password' };
421
+ }
422
+ }
423
+ }
424
+ }
425
+
426
+ // 优先级 1.5: 页面内包含“密码”的各类交互链接 (a, button, span.fui-Link 等)
427
+ const pwdMarkers = [
428
+ '使用密码',
429
+ '改用密码',
430
+ '密码登录',
431
+ '输入你的密码',
432
+ '输入密码',
433
+ '使用你的密码',
434
+ 'use your password',
435
+ 'use password',
436
+ 'use your password instead',
437
+ 'sign in with password',
438
+ 'sign in with your password',
439
+ ];
440
+
441
+ const interactiveNodes = Array.from(document.querySelectorAll('[role="button"], button, a, span.fui-Link, div[role="button"]'));
442
+ for (const el of interactiveNodes) {
443
+ if (!isVisible(el)) continue;
444
+ const text = (el.innerText || el.textContent || el.getAttribute('aria-label') || '').trim().replace(/\\s+/g, ' ').toLowerCase();
445
+ for (const m of pwdMarkers) {
446
+ if (text === m || (text.includes(m) && text.length <= m.length + 10)) {
447
+ doClick(el);
448
+ const r = el.getBoundingClientRect();
449
+ return { point: { x: r.left + r.width / 2, y: r.top + r.height / 2 }, type: 'password' };
450
+ }
451
+ }
452
+ }
453
+
454
+ // 优先级 2: 若未找到直接的密码入口,点击“其他登录方式 / Sign in another way”展开凭据选择列表
455
+ const anotherWaySelectors = ['#signInAnotherWay', '#idA_PWD_SwitchToCredPicker'];
456
+ for (const sel of anotherWaySelectors) {
457
+ const el = document.querySelector(sel);
458
+ if (isVisible(el)) {
459
+ doClick(el);
460
+ const r = el.getBoundingClientRect();
461
+ return { point: { x: r.left + r.width / 2, y: r.top + r.height / 2 }, type: 'another_way' };
462
+ }
463
+ }
464
+
465
+ const anotherMarkers = [
466
+ '使用另一种方式登录',
467
+ '使用其他方式登录',
468
+ '其他登录方式',
469
+ '其他方式',
470
+ '通过其他方式登录',
471
+ 'sign in another way',
472
+ 'other ways to sign in',
473
+ ];
474
+ for (const el of interactiveNodes) {
475
+ if (!isVisible(el)) continue;
476
+ const text = (el.innerText || el.textContent || el.getAttribute('aria-label') || '').trim().replace(/\\s+/g, ' ').toLowerCase();
477
+ for (const m of anotherMarkers) {
478
+ if (text === m || (text.includes(m) && text.length <= m.length + 10)) {
479
+ doClick(el);
480
+ const r = el.getBoundingClientRect();
481
+ return { point: { x: r.left + r.width / 2, y: r.top + r.height / 2 }, type: 'another_way' };
482
+ }
483
+ }
484
+ }
485
+
486
+ return null;
542
487
  })()`);
543
- if (point && typeof point.x === 'number' && typeof point.y === 'number') {
544
- // 使用原生 CDP 鼠标事件模拟真实用户物理点击
545
- await cdp.clickPoint(point.x, point.y);
546
- return true;
488
+ if (res && res.point) {
489
+ await cdp.clickPoint(res.point.x, res.point.y);
490
+ return { clicked: true, type: res.type };
547
491
  }
548
- return false;
492
+ return { clicked: false };
549
493
  }
550
494
  catch {
551
- return false;
495
+ return { clicked: false };
552
496
  }
553
497
  }
554
- /**
555
- * 格式化打印操作结果卡片
556
- */
557
498
  static printResultCard(result) {
558
499
  if (result.status === 'logged_in') {
559
500
  console.log(boxen([
@@ -611,60 +552,93 @@ export class OutlookLauncher {
611
552
  }));
612
553
  }
613
554
  }
614
- /**
615
- * 在已到达 Outlook 收件箱页面时,利用 CDP 实时嗅探 Cursor / WorkOS 最新的 6 位数字验证码
616
- */
617
- static async sniffVerificationCode(cdp, timeoutMs = 20000) {
555
+ static async sniffVerificationCode(cdp, timeoutMs = 35000) {
618
556
  const end = Date.now() + timeoutMs;
619
- console.log(chalk.cyan(' → 浏览器已成功进入收件箱,正在实时探测 Cursor 邮件验证码...'));
620
- // 等待 1.5 秒让 Outlook 单页应用渲染出邮件列表
621
- await new Promise((r) => setTimeout(r, 1500));
557
+ console.log(chalk.cyan(' → 浏览器已成功进入收件箱,正在全自动嗅探提取 6 位验证码...'));
558
+ let attempt = 0;
559
+ let hasSwitchedToOther = false;
560
+ await new Promise((r) => setTimeout(r, 1200));
622
561
  while (Date.now() < end) {
562
+ attempt++;
623
563
  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;
564
+ if (attempt >= 2 && !hasSwitchedToOther) {
565
+ const switched = await cdp.evaluate(`(() => {
566
+ const tabs = Array.from(document.querySelectorAll('button, div[role="tab"], span[role="tab"], a, [aria-label*="其他"], [aria-label*="Other"]'));
567
+ for (const t of tabs) {
568
+ const text = ((t.innerText || t.textContent || t.getAttribute('aria-label') || '').trim());
569
+ if (text === '其他' || text === 'Other' || text.startsWith('其他') || text.startsWith('Other')) {
570
+ const isSelected = t.getAttribute('aria-selected') === 'true' || t.classList.contains('is-selected') || t.classList.contains('active');
571
+ if (!isSelected) {
572
+ (t as HTMLElement).click();
573
+ return true;
574
+ }
575
+ }
576
+ }
577
+ return false;
578
+ })()`);
579
+ if (switched) {
580
+ hasSwitchedToOther = true;
581
+ console.log(chalk.grey(' → 正在自动巡检【其他 / Other】邮件分类栏...'));
582
+ await new Promise((r) => setTimeout(r, 1000));
583
+ }
584
+ }
585
+ const found = await cdp.evaluate(`(() => {
586
+ // 1. 全文/阅读窗格直接正则提取 (包括列表摘要及展开后的卡片正文)
587
+ const fullText = (document.body ? (document.body.innerText + '\\n' + document.body.textContent) : '');
588
+
589
+ // 1.1 精准匹配 Cursor 官方模板规则 (例如: "Your one-time code is 298372" / "Your code is 298372")
590
+ const directMatch = fullText.match(/(?:one-time code is|code is|your code is|one-time code|验证码为|验证码是|验证代码为|验证代码是)[^\\d]{0,25}(\\d{6})\\b/i);
591
+ if (directMatch && directMatch[1]) {
592
+ return directMatch[1];
593
+ }
594
+
595
+ // 2. 检查邮件列表项 (左侧邮件列表)
596
+ const mailItems = Array.from(document.querySelectorAll('div[role="option"], div[data-convid], div[aria-label*="Cursor"], div[aria-label*="cursor"], div[draggable="true"]'));
597
+ for (const item of mailItems) {
598
+ const label = ((item.getAttribute('aria-label') || '') + ' ' + (item.innerText || '')).trim();
599
+ if (/cursor|workos|sign in to cursor/i.test(label)) {
600
+ // 邮件列表项的摘要预览文本中通常直接包含: "Your one-time code is 298372. Th..."
601
+ const m = label.match(/(?:one-time code is|code is|code\\s*|验证码[::\\s]*|\\b)(\\d{6})\\b/i);
602
+ if (m && m[1]) {
603
+ return m[1];
604
+ }
605
+ // 尝试点选该邮件项展开阅读窗格
606
+ try { (item as HTMLElement).click(); } catch {}
607
+ }
608
+ }
609
+
610
+ // 3. 检查右侧阅读窗格或大号突出数字 (卡片大字号)
611
+ const readingPanes = Array.from(document.querySelectorAll('div[role="region"], div[data-app-section="ConversationReadingPane"], div[aria-label*="邮件内容"], div[aria-label*="Reading"], #Item\\\\.MessageUniqueBody, div[aria-label*="Cursor"]'));
612
+ for (const rp of readingPanes) {
613
+ const text = (rp as HTMLElement).innerText || '';
614
+ if (/cursor|one-time code|sign in/i.test(text)) {
615
+ const m = text.match(/(?:code is|one-time code|验证码)[^\\d]{0,40}(\\d{6})\\b/i) || text.match(/\\b(\\d{6})\\b/);
616
+ if (m && m[1]) return m[1];
617
+ }
618
+ }
619
+
620
+ // 4. 检查可能嵌套在 iframe 里的邮件正文 (部分 Outlook 版本的正文置于隔离 iframe)
621
+ const iframes = Array.from(document.querySelectorAll('iframe'));
622
+ for (const f of iframes) {
623
+ try {
624
+ const doc = f.contentDocument || f.contentWindow?.document;
625
+ if (doc && doc.body) {
626
+ const iText = doc.body.innerText || doc.body.textContent || '';
627
+ const m = iText.match(/(?:one-time code is|code is|one-time code|验证码)[^\\d]{0,25}(\\d{6})\\b/i) ||
628
+ (iText.includes('Cursor') ? iText.match(/\\b(\\d{6})\\b/) : null);
629
+ if (m && m[1]) return m[1];
630
+ }
631
+ } catch {}
632
+ }
633
+
634
+ return null;
661
635
  })()`);
662
636
  if (found && /^\d{6}$/.test(found)) {
663
637
  return found;
664
638
  }
665
639
  }
666
640
  catch { }
667
- await new Promise((r) => setTimeout(r, 1500));
641
+ await new Promise((r) => setTimeout(r, 1000));
668
642
  }
669
643
  return null;
670
644
  }