signup-page.js 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. // content/signup-page.js — Content script for OpenAI auth pages (steps 2, 3, 4-receive, 5)
  2. // Injected on: auth0.openai.com, auth.openai.com, accounts.openai.com
  3. console.log('[MultiPage:signup-page] Content script loaded on', location.href);
  4. // Listen for commands from Background
  5. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  6. if (
  7. message.type === 'EXECUTE_STEP'
  8. || message.type === 'FILL_CODE'
  9. || message.type === 'STEP8_FIND_AND_CLICK'
  10. || message.type === 'STEP8_GET_STATE'
  11. || message.type === 'STEP8_TRIGGER_CONTINUE'
  12. || message.type === 'PREPARE_LOGIN_CODE'
  13. || message.type === 'PREPARE_SIGNUP_VERIFICATION'
  14. || message.type === 'RESEND_VERIFICATION_CODE'
  15. ) {
  16. resetStopState();
  17. handleCommand(message).then((result) => {
  18. sendResponse({ ok: true, ...(result || {}) });
  19. }).catch(err => {
  20. if (isStopError(err)) {
  21. log(`步骤 ${message.step || 8}:已被用户停止。`, 'warn');
  22. sendResponse({ stopped: true, error: err.message });
  23. return;
  24. }
  25. if (message.type === 'STEP8_FIND_AND_CLICK') {
  26. log(`步骤 8:${err.message}`, 'error');
  27. sendResponse({ error: err.message });
  28. return;
  29. }
  30. reportError(message.step, err.message);
  31. sendResponse({ error: err.message });
  32. });
  33. return true;
  34. }
  35. });
  36. async function handleCommand(message) {
  37. switch (message.type) {
  38. case 'EXECUTE_STEP':
  39. switch (message.step) {
  40. case 2: return await step2_clickRegister();
  41. case 3: return await step3_fillEmailPassword(message.payload);
  42. case 5: return await step5_fillNameBirthday(message.payload);
  43. case 6: return await step6_login(message.payload);
  44. case 8: return await step8_findAndClick();
  45. default: throw new Error(`signup-page.js 不处理步骤 ${message.step}`);
  46. }
  47. case 'FILL_CODE':
  48. // Step 4 = signup code, Step 7 = login code (same handler)
  49. return await fillVerificationCode(message.step, message.payload);
  50. case 'PREPARE_SIGNUP_VERIFICATION':
  51. return await prepareSignupVerificationFlow(message.payload);
  52. case 'PREPARE_LOGIN_CODE':
  53. return await prepareLoginCodeFlow();
  54. case 'RESEND_VERIFICATION_CODE':
  55. return await resendVerificationCode(message.step);
  56. case 'STEP8_FIND_AND_CLICK':
  57. return await step8_findAndClick();
  58. case 'STEP8_GET_STATE':
  59. return getStep8State();
  60. case 'STEP8_TRIGGER_CONTINUE':
  61. return await step8_triggerContinue(message.payload);
  62. }
  63. }
  64. const VERIFICATION_CODE_INPUT_SELECTOR = [
  65. 'input[name="code"]',
  66. 'input[name="otp"]',
  67. 'input[autocomplete="one-time-code"]',
  68. 'input[type="text"][maxlength="6"]',
  69. 'input[type="tel"][maxlength="6"]',
  70. 'input[aria-label*="code" i]',
  71. 'input[placeholder*="code" i]',
  72. 'input[inputmode="numeric"]',
  73. ].join(', ');
  74. const ONE_TIME_CODE_LOGIN_PATTERN = /使用一次性验证码登录|改用(?:一次性)?验证码(?:登录)?|使用验证码登录|一次性验证码|验证码登录|one[-\s]*time\s*(?:passcode|password|code)|use\s+(?:a\s+)?one[-\s]*time\s*(?:passcode|password|code)(?:\s+instead)?|use\s+(?:a\s+)?code(?:\s+instead)?|sign\s+in\s+with\s+(?:email|code)|email\s+(?:me\s+)?(?:a\s+)?code/i;
  75. const RESEND_VERIFICATION_CODE_PATTERN = /重新发送(?:验证码)?|再次发送(?:验证码)?|重发(?:验证码)?|未收到(?:验证码|邮件)|resend(?:\s+code)?|send\s+(?:a\s+)?new\s+code|send\s+(?:it\s+)?again|request\s+(?:a\s+)?new\s+code|didn'?t\s+receive/i;
  76. function isVisibleElement(el) {
  77. if (!el) return false;
  78. const style = window.getComputedStyle(el);
  79. const rect = el.getBoundingClientRect();
  80. return style.display !== 'none'
  81. && style.visibility !== 'hidden'
  82. && rect.width > 0
  83. && rect.height > 0;
  84. }
  85. function getVerificationCodeTarget() {
  86. const codeInput = document.querySelector(VERIFICATION_CODE_INPUT_SELECTOR);
  87. if (codeInput && isVisibleElement(codeInput)) {
  88. return { type: 'single', element: codeInput };
  89. }
  90. const singleInputs = Array.from(document.querySelectorAll('input[maxlength="1"]'))
  91. .filter(isVisibleElement);
  92. if (singleInputs.length >= 6) {
  93. return { type: 'split', elements: singleInputs };
  94. }
  95. return null;
  96. }
  97. function getActionText(el) {
  98. return [
  99. el?.textContent,
  100. el?.value,
  101. el?.getAttribute?.('aria-label'),
  102. el?.getAttribute?.('title'),
  103. ]
  104. .filter(Boolean)
  105. .join(' ')
  106. .replace(/\s+/g, ' ')
  107. .trim();
  108. }
  109. function isActionEnabled(el) {
  110. return Boolean(el)
  111. && !el.disabled
  112. && el.getAttribute('aria-disabled') !== 'true';
  113. }
  114. function findOneTimeCodeLoginTrigger() {
  115. const candidates = document.querySelectorAll(
  116. 'button, a, [role="button"], [role="link"], input[type="button"], input[type="submit"]'
  117. );
  118. for (const el of candidates) {
  119. if (!isVisibleElement(el)) continue;
  120. if (el.disabled || el.getAttribute('aria-disabled') === 'true') continue;
  121. const text = [
  122. el.textContent,
  123. el.value,
  124. el.getAttribute('aria-label'),
  125. el.getAttribute('title'),
  126. ]
  127. .filter(Boolean)
  128. .join(' ')
  129. .replace(/\s+/g, ' ')
  130. .trim();
  131. if (text && ONE_TIME_CODE_LOGIN_PATTERN.test(text)) {
  132. return el;
  133. }
  134. }
  135. return null;
  136. }
  137. function findResendVerificationCodeTrigger({ allowDisabled = false } = {}) {
  138. const candidates = document.querySelectorAll(
  139. 'button, a, [role="button"], [role="link"], input[type="button"], input[type="submit"]'
  140. );
  141. for (const el of candidates) {
  142. if (!isVisibleElement(el)) continue;
  143. if (!allowDisabled && !isActionEnabled(el)) continue;
  144. const text = getActionText(el);
  145. if (text && RESEND_VERIFICATION_CODE_PATTERN.test(text)) {
  146. return el;
  147. }
  148. }
  149. return null;
  150. }
  151. function isEmailVerificationPage() {
  152. return /\/email-verification(?:[/?#]|$)/i.test(location.pathname || '');
  153. }
  154. async function prepareLoginCodeFlow(timeout = 15000) {
  155. const readyTarget = getVerificationCodeTarget();
  156. if (readyTarget) {
  157. log('步骤 7:验证码输入框已就绪。');
  158. return { ready: true, mode: readyTarget.type };
  159. }
  160. if (isEmailVerificationPage() && isVerificationPageStillVisible()) {
  161. log('步骤 7:已进入邮箱验证码页面,正在等待验证码输入框或重发入口稳定。');
  162. return { ready: true, mode: 'verification_page' };
  163. }
  164. const initialRestartSignal = getStep7RestartFromStep6Signal();
  165. if (initialRestartSignal) {
  166. log('步骤 7:检测到登录页超时报错,准备回到步骤 6 重新发起登录验证码流程...', 'warn');
  167. return initialRestartSignal;
  168. }
  169. const start = Date.now();
  170. let switchClickCount = 0;
  171. let lastSwitchAttemptAt = 0;
  172. let loggedPasswordPage = false;
  173. let loggedVerificationPage = false;
  174. while (Date.now() - start < timeout) {
  175. throwIfStopped();
  176. const target = getVerificationCodeTarget();
  177. if (target) {
  178. log('步骤 7:验证码页面已就绪。');
  179. return { ready: true, mode: target.type };
  180. }
  181. if (isEmailVerificationPage() && isVerificationPageStillVisible()) {
  182. if (!loggedVerificationPage) {
  183. loggedVerificationPage = true;
  184. log('步骤 7:页面已进入邮箱验证码流程,继续等待验证码输入框渲染...');
  185. }
  186. await sleep(250);
  187. continue;
  188. }
  189. const restartSignal = getStep7RestartFromStep6Signal();
  190. if (restartSignal) {
  191. log('步骤 7:检测到登录页超时报错,准备回到步骤 6 重新发起登录验证码流程...', 'warn');
  192. return restartSignal;
  193. }
  194. const passwordInput = document.querySelector('input[type="password"]');
  195. const switchTrigger = findOneTimeCodeLoginTrigger();
  196. if (switchTrigger && (switchClickCount === 0 || Date.now() - lastSwitchAttemptAt > 1500)) {
  197. switchClickCount += 1;
  198. lastSwitchAttemptAt = Date.now();
  199. loggedPasswordPage = false;
  200. log('步骤 7:检测到密码页,正在切换到一次性验证码登录...');
  201. await humanPause(350, 900);
  202. simulateClick(switchTrigger);
  203. await sleep(1200);
  204. continue;
  205. }
  206. if (passwordInput && !loggedPasswordPage) {
  207. loggedPasswordPage = true;
  208. log('步骤 7:正在等待密码页上的一次性验证码登录入口...');
  209. }
  210. await sleep(200);
  211. }
  212. throw new Error('无法切换到一次性验证码验证页面。URL: ' + location.href);
  213. }
  214. async function resendVerificationCode(step, timeout = 45000) {
  215. if (step === 7) {
  216. const prepareResult = await prepareLoginCodeFlow();
  217. if (prepareResult?.restartFromStep6) {
  218. return prepareResult;
  219. }
  220. }
  221. const start = Date.now();
  222. let action = null;
  223. let loggedWaiting = false;
  224. while (Date.now() - start < timeout) {
  225. throwIfStopped();
  226. action = findResendVerificationCodeTrigger({ allowDisabled: true });
  227. if (action && isActionEnabled(action)) {
  228. log(`步骤 ${step}:重新发送验证码按钮已可用。`);
  229. await humanPause(350, 900);
  230. simulateClick(action);
  231. await sleep(1200);
  232. return {
  233. resent: true,
  234. buttonText: getActionText(action),
  235. };
  236. }
  237. if (action && !loggedWaiting) {
  238. loggedWaiting = true;
  239. log(`步骤 ${step}:正在等待重新发送验证码按钮变为可点击...`);
  240. }
  241. await sleep(250);
  242. }
  243. throw new Error('无法点击重新发送验证码按钮。URL: ' + location.href);
  244. }
  245. // ============================================================
  246. // Step 2: Click Register
  247. // ============================================================
  248. async function step2_clickRegister() {
  249. log('步骤 2:正在查找注册按钮...');
  250. let registerBtn = null;
  251. try {
  252. registerBtn = await waitForElementByText(
  253. 'a, button, [role="button"], [role="link"]',
  254. /sign\s*up|register|create\s*account|注册/i,
  255. 10000
  256. );
  257. } catch {
  258. // Some pages may have a direct link
  259. try {
  260. registerBtn = await waitForElement('a[href*="signup"], a[href*="register"]', 5000);
  261. } catch {
  262. throw new Error(
  263. '未找到注册按钮。' +
  264. '请在 DevTools 中检查认证页面 DOM。URL: ' + location.href
  265. );
  266. }
  267. }
  268. await humanPause(450, 1200);
  269. reportComplete(2);
  270. simulateClick(registerBtn);
  271. log('步骤 2:已点击注册按钮');
  272. }
  273. // ============================================================
  274. // Step 3: Fill Email & Password
  275. // ============================================================
  276. async function step3_fillEmailPassword(payload) {
  277. const { email } = payload;
  278. if (!email) throw new Error('未提供邮箱地址,请先在侧边栏粘贴邮箱。');
  279. log(`步骤 3:正在填写邮箱:${email}`);
  280. // Find email input
  281. let emailInput = null;
  282. try {
  283. emailInput = await waitForElement(
  284. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email"], input[placeholder*="Email"]',
  285. 10000
  286. );
  287. } catch {
  288. throw new Error('在注册页未找到邮箱输入框。URL: ' + location.href);
  289. }
  290. await humanPause(500, 1400);
  291. fillInput(emailInput, email);
  292. log('步骤 3:邮箱已填写');
  293. // Check if password field is on the same page
  294. let passwordInput = document.querySelector('input[type="password"]');
  295. if (!passwordInput) {
  296. // Need to submit email first to get to password page
  297. log('步骤 3:暂未发现密码输入框,先提交邮箱...');
  298. const submitBtn = document.querySelector('button[type="submit"]')
  299. || await waitForElementByText('button', /continue|next|submit|继续|下一步/i, 5000).catch(() => null);
  300. if (submitBtn) {
  301. await humanPause(400, 1100);
  302. simulateClick(submitBtn);
  303. log('步骤 3:邮箱已提交,正在等待密码输入框...');
  304. await sleep(2000);
  305. }
  306. try {
  307. passwordInput = await waitForElement('input[type="password"]', 10000);
  308. } catch {
  309. throw new Error('提交邮箱后仍未找到密码输入框。URL: ' + location.href);
  310. }
  311. }
  312. if (!payload.password) throw new Error('未提供密码,步骤 3 需要可用密码。');
  313. await humanPause(600, 1500);
  314. fillInput(passwordInput, payload.password);
  315. log('步骤 3:密码已填写');
  316. // Report complete BEFORE submit, because submit causes page navigation
  317. // which kills the content script connection
  318. reportComplete(3, { email });
  319. // Submit the form (page will navigate away after this)
  320. await sleep(500);
  321. const submitBtn = document.querySelector('button[type="submit"]')
  322. || await waitForElementByText('button', /continue|sign\s*up|submit|注册|创建|create/i, 5000).catch(() => null);
  323. if (submitBtn) {
  324. await humanPause(500, 1300);
  325. simulateClick(submitBtn);
  326. log('步骤 3:表单已提交');
  327. }
  328. }
  329. // ============================================================
  330. // Fill Verification Code (used by step 4 and step 7)
  331. // ============================================================
  332. const INVALID_VERIFICATION_CODE_PATTERN = /代码不正确|验证码不正确|验证码错误|code\s+(?:is\s+)?incorrect|invalid\s+code|incorrect\s+code|try\s+again/i;
  333. const VERIFICATION_PAGE_PATTERN = /检查您的收件箱|输入我们刚刚向|重新发送电子邮件|重新发送验证码|验证码|代码不正确|email\s+verification/i;
  334. const OAUTH_CONSENT_PAGE_PATTERN = /使用\s*ChatGPT\s*登录到\s*Codex|login\s+to\s+codex|log\s+in\s+to\s+codex|authorize|授权/i;
  335. const ADD_PHONE_PAGE_PATTERN = /add[\s-]*phone|添加手机号|手机号码|手机号|phone\s+number|telephone/i;
  336. const STEP5_SUBMIT_ERROR_PATTERN = /无法根据该信息创建帐户|请重试|unable\s+to\s+create\s+(?:your\s+)?account|couldn'?t\s+create\s+(?:your\s+)?account|something\s+went\s+wrong|invalid\s+(?:birthday|birth|date)|生日|出生日期/i;
  337. const AUTH_TIMEOUT_ERROR_TITLE_PATTERN = /糟糕,出错了|something\s+went\s+wrong|oops/i;
  338. const AUTH_TIMEOUT_ERROR_DETAIL_PATTERN = /operation\s+timed\s+out|timed\s+out|请求超时|操作超时/i;
  339. const SIGNUP_EMAIL_EXISTS_PATTERN = /与此电子邮件地址相关联的帐户已存在|account\s+associated\s+with\s+this\s+email\s+address\s+already\s+exists|email\s+address.*already\s+exists/i;
  340. function getVerificationErrorText() {
  341. const messages = [];
  342. const selectors = [
  343. '.react-aria-FieldError',
  344. '[slot="errorMessage"]',
  345. '[id$="-error"]',
  346. '[data-invalid="true"] + *',
  347. '[aria-invalid="true"] + *',
  348. '[class*="error"]',
  349. ];
  350. for (const selector of selectors) {
  351. document.querySelectorAll(selector).forEach((el) => {
  352. const text = (el.textContent || '').replace(/\s+/g, ' ').trim();
  353. if (text) {
  354. messages.push(text);
  355. }
  356. });
  357. }
  358. const invalidInput = document.querySelector(`${VERIFICATION_CODE_INPUT_SELECTOR}[aria-invalid="true"], ${VERIFICATION_CODE_INPUT_SELECTOR}[data-invalid="true"]`);
  359. if (invalidInput) {
  360. const wrapper = invalidInput.closest('form, [data-rac], ._root_18qcl_51, div');
  361. if (wrapper) {
  362. const text = (wrapper.textContent || '').replace(/\s+/g, ' ').trim();
  363. if (text) {
  364. messages.push(text);
  365. }
  366. }
  367. }
  368. return messages.find((text) => INVALID_VERIFICATION_CODE_PATTERN.test(text)) || '';
  369. }
  370. function isStep5Ready() {
  371. return Boolean(
  372. document.querySelector('input[name="name"], input[autocomplete="name"], input[name="birthday"], input[name="age"], [role="spinbutton"][data-type="year"]')
  373. );
  374. }
  375. function getPageTextSnapshot() {
  376. return (document.body?.innerText || document.body?.textContent || '')
  377. .replace(/\s+/g, ' ')
  378. .trim();
  379. }
  380. function getPrimaryContinueButton() {
  381. const continueBtn = document.querySelector(
  382. 'button[type="submit"][data-dd-action-name="Continue"], button[type="submit"]._primary_3rdp0_107'
  383. );
  384. if (continueBtn && isVisibleElement(continueBtn)) {
  385. return continueBtn;
  386. }
  387. const buttons = document.querySelectorAll('button, [role="button"]');
  388. return Array.from(buttons).find((el) => isVisibleElement(el) && /继续|Continue/i.test(el.textContent || '')) || null;
  389. }
  390. function isVerificationPageStillVisible() {
  391. if (getVerificationCodeTarget()) return true;
  392. if (findResendVerificationCodeTrigger({ allowDisabled: true })) return true;
  393. if (document.querySelector('form[action*="email-verification" i]')) return true;
  394. return VERIFICATION_PAGE_PATTERN.test(getPageTextSnapshot());
  395. }
  396. function isAddPhonePageReady() {
  397. const path = `${location.pathname || ''} ${location.href || ''}`;
  398. if (/\/add-phone(?:[/?#]|$)/i.test(path)) return true;
  399. const phoneInput = document.querySelector(
  400. 'input[type="tel"]:not([maxlength="6"]), input[name*="phone" i], input[id*="phone" i], input[autocomplete="tel"]'
  401. );
  402. if (phoneInput && isVisibleElement(phoneInput)) {
  403. return true;
  404. }
  405. return ADD_PHONE_PAGE_PATTERN.test(getPageTextSnapshot());
  406. }
  407. function isLoginPage() {
  408. return /\/log-in(?:[/?#]|$)/i.test(location.pathname || '');
  409. }
  410. function isStep8Ready() {
  411. const continueBtn = getPrimaryContinueButton();
  412. if (!continueBtn) return false;
  413. if (isVerificationPageStillVisible()) return false;
  414. if (isAddPhonePageReady()) return false;
  415. return OAUTH_CONSENT_PAGE_PATTERN.test(getPageTextSnapshot());
  416. }
  417. function normalizeInlineText(text) {
  418. return (text || '').replace(/\s+/g, ' ').trim();
  419. }
  420. function findBirthdayReactAriaSelect(labelText) {
  421. const normalizedLabel = normalizeInlineText(labelText);
  422. const roots = document.querySelectorAll('.react-aria-Select');
  423. for (const root of roots) {
  424. const labelEl = Array.from(root.querySelectorAll('span')).find((el) => normalizeInlineText(el.textContent) === normalizedLabel);
  425. if (!labelEl) continue;
  426. const item = root.closest('[class*="selectItem"], ._selectItem_ppsls_113') || root.parentElement;
  427. const nativeSelect = item?.querySelector('[data-testid="hidden-select-container"] select') || null;
  428. const button = root.querySelector('button[aria-haspopup="listbox"]') || null;
  429. const valueEl = root.querySelector('.react-aria-SelectValue') || null;
  430. return { root, item, labelEl, nativeSelect, button, valueEl };
  431. }
  432. return null;
  433. }
  434. async function setReactAriaBirthdaySelect(control, value) {
  435. if (!control?.nativeSelect) {
  436. throw new Error('未找到可写入的生日下拉框。');
  437. }
  438. const desiredValue = String(value);
  439. const option = Array.from(control.nativeSelect.options).find((item) => item.value === desiredValue);
  440. if (!option) {
  441. throw new Error(`生日下拉框中不存在值 ${desiredValue}。`);
  442. }
  443. control.nativeSelect.value = desiredValue;
  444. option.selected = true;
  445. control.nativeSelect.dispatchEvent(new Event('input', { bubbles: true }));
  446. control.nativeSelect.dispatchEvent(new Event('change', { bubbles: true }));
  447. await sleep(120);
  448. }
  449. function getStep5ErrorText() {
  450. const messages = [];
  451. const selectors = [
  452. '.react-aria-FieldError',
  453. '[slot="errorMessage"]',
  454. '[id$="-error"]',
  455. '[id$="-errors"]',
  456. '[role="alert"]',
  457. '[aria-live="assertive"]',
  458. '[aria-live="polite"]',
  459. '[class*="error"]',
  460. ];
  461. for (const selector of selectors) {
  462. document.querySelectorAll(selector).forEach((el) => {
  463. if (!isVisibleElement(el)) return;
  464. const text = normalizeInlineText(el.textContent);
  465. if (text) {
  466. messages.push(text);
  467. }
  468. });
  469. }
  470. const invalidField = Array.from(document.querySelectorAll('[aria-invalid="true"], [data-invalid="true"]'))
  471. .find((el) => isVisibleElement(el));
  472. if (invalidField) {
  473. const wrapper = invalidField.closest('form, fieldset, [data-rac], div');
  474. if (wrapper) {
  475. const text = normalizeInlineText(wrapper.textContent);
  476. if (text) {
  477. messages.push(text);
  478. }
  479. }
  480. }
  481. return messages.find((text) => STEP5_SUBMIT_ERROR_PATTERN.test(text)) || '';
  482. }
  483. async function waitForStep5SubmitOutcome(timeout = 15000) {
  484. const start = Date.now();
  485. while (Date.now() - start < timeout) {
  486. throwIfStopped();
  487. const errorText = getStep5ErrorText();
  488. if (errorText) {
  489. return { invalidProfile: true, errorText };
  490. }
  491. if (isAddPhonePageReady()) {
  492. return { success: true, addPhonePage: true };
  493. }
  494. if (isStep8Ready()) {
  495. return { success: true };
  496. }
  497. await sleep(150);
  498. }
  499. const errorText = getStep5ErrorText();
  500. if (errorText) {
  501. return { invalidProfile: true, errorText };
  502. }
  503. return {
  504. invalidProfile: true,
  505. errorText: '提交后未进入下一阶段,请检查生日是否真正被页面接受。',
  506. };
  507. }
  508. function isSignupPasswordPage() {
  509. return /\/create-account\/password(?:[/?#]|$)/i.test(location.pathname || '');
  510. }
  511. function getSignupPasswordInput() {
  512. const input = document.querySelector('input[type="password"]');
  513. return input && isVisibleElement(input) ? input : null;
  514. }
  515. function getSignupPasswordSubmitButton({ allowDisabled = false } = {}) {
  516. const direct = document.querySelector('button[type="submit"]');
  517. if (direct && isVisibleElement(direct) && (allowDisabled || isActionEnabled(direct))) {
  518. return direct;
  519. }
  520. const candidates = document.querySelectorAll('button, [role="button"]');
  521. return Array.from(candidates).find((el) => {
  522. if (!isVisibleElement(el) || (!allowDisabled && !isActionEnabled(el))) return false;
  523. const text = getActionText(el);
  524. return /继续|continue|submit|创建|create/i.test(text);
  525. }) || null;
  526. }
  527. function getAuthRetryButton({ allowDisabled = false } = {}) {
  528. const direct = document.querySelector('button[data-dd-action-name="Try again"]');
  529. if (direct && isVisibleElement(direct) && (allowDisabled || isActionEnabled(direct))) {
  530. return direct;
  531. }
  532. const candidates = document.querySelectorAll('button, [role="button"]');
  533. return Array.from(candidates).find((el) => {
  534. if (!isVisibleElement(el) || (!allowDisabled && !isActionEnabled(el))) return false;
  535. const text = getActionText(el);
  536. return /重试|try\s+again/i.test(text);
  537. }) || null;
  538. }
  539. function matchesAuthTimeoutErrorPage(pathPattern) {
  540. if (!pathPattern.test(location.pathname || '')) return false;
  541. const text = getPageTextSnapshot();
  542. return Boolean(
  543. getAuthRetryButton({ allowDisabled: true })
  544. && (AUTH_TIMEOUT_ERROR_TITLE_PATTERN.test(text)
  545. || AUTH_TIMEOUT_ERROR_DETAIL_PATTERN.test(text)
  546. || AUTH_TIMEOUT_ERROR_TITLE_PATTERN.test(document.title || ''))
  547. );
  548. }
  549. function isSignupPasswordErrorPage() {
  550. return matchesAuthTimeoutErrorPage(/\/create-account\/password(?:[/?#]|$)/i);
  551. }
  552. function buildStep7RestartFromStep6Marker(reason, url = location.href) {
  553. return `STEP7_RESTART_FROM_STEP6::${reason || 'unknown'}::${url || ''}`;
  554. }
  555. function getStep7RestartFromStep6Signal() {
  556. if (!isLoginPage() || !matchesAuthTimeoutErrorPage(/\/log-in(?:[/?#]|$)/i)) {
  557. return null;
  558. }
  559. return {
  560. error: buildStep7RestartFromStep6Marker('login_timeout_error_page', location.href),
  561. restartFromStep6: true,
  562. reason: 'login_timeout_error_page',
  563. url: location.href,
  564. };
  565. }
  566. function isSignupEmailAlreadyExistsPage() {
  567. return isSignupPasswordPage() && SIGNUP_EMAIL_EXISTS_PATTERN.test(getPageTextSnapshot());
  568. }
  569. function inspectSignupVerificationState() {
  570. if (isStep5Ready()) {
  571. return { state: 'step5' };
  572. }
  573. if (isVerificationPageStillVisible()) {
  574. return { state: 'verification' };
  575. }
  576. if (isSignupPasswordErrorPage()) {
  577. return {
  578. state: 'error',
  579. retryButton: getAuthRetryButton({ allowDisabled: true }),
  580. };
  581. }
  582. if (isSignupEmailAlreadyExistsPage()) {
  583. return { state: 'email_exists' };
  584. }
  585. const passwordInput = getSignupPasswordInput();
  586. if (passwordInput) {
  587. return {
  588. state: 'password',
  589. passwordInput,
  590. submitButton: getSignupPasswordSubmitButton({ allowDisabled: true }),
  591. };
  592. }
  593. return { state: 'unknown' };
  594. }
  595. async function waitForSignupVerificationTransition(timeout = 5000) {
  596. const start = Date.now();
  597. while (Date.now() - start < timeout) {
  598. throwIfStopped();
  599. const snapshot = inspectSignupVerificationState();
  600. if (snapshot.state === 'step5' || snapshot.state === 'verification' || snapshot.state === 'error' || snapshot.state === 'email_exists') {
  601. return snapshot;
  602. }
  603. await sleep(200);
  604. }
  605. return inspectSignupVerificationState();
  606. }
  607. async function prepareSignupVerificationFlow(payload = {}, timeout = 30000) {
  608. const { password } = payload;
  609. const start = Date.now();
  610. let recoveryRound = 0;
  611. const maxRecoveryRounds = 3;
  612. while (Date.now() - start < timeout && recoveryRound < maxRecoveryRounds) {
  613. throwIfStopped();
  614. const roundNo = recoveryRound + 1;
  615. log(`步骤 4:等待页面进入验证码阶段(第 ${roundNo}/${maxRecoveryRounds} 轮,先等待 5 秒)...`, 'info');
  616. const snapshot = await waitForSignupVerificationTransition(5000);
  617. if (snapshot.state === 'step5') {
  618. log('步骤 4:页面已进入验证码后的下一阶段,本步骤按已完成处理。', 'ok');
  619. return { ready: true, alreadyVerified: true, retried: recoveryRound };
  620. }
  621. if (snapshot.state === 'verification') {
  622. log(`步骤 4:验证码页面已就绪${recoveryRound ? `(期间自动恢复 ${recoveryRound} 次)` : ''}。`, 'ok');
  623. return { ready: true, retried: recoveryRound };
  624. }
  625. if (snapshot.state === 'email_exists') {
  626. throw new Error('当前邮箱已存在,需要重新开始新一轮。');
  627. }
  628. recoveryRound += 1;
  629. if (snapshot.state === 'error') {
  630. if (snapshot.retryButton && isActionEnabled(snapshot.retryButton)) {
  631. log(`步骤 4:检测到密码页超时报错,正在点击“重试”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  632. await humanPause(350, 900);
  633. simulateClick(snapshot.retryButton);
  634. await sleep(1200);
  635. continue;
  636. }
  637. log(`步骤 4:检测到异常页,但“重试”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  638. continue;
  639. }
  640. if (snapshot.state === 'password') {
  641. if (!password) {
  642. throw new Error('当前回到了密码页,但没有可用密码,无法自动重新提交。');
  643. }
  644. if ((snapshot.passwordInput.value || '') !== password) {
  645. log('步骤 4:页面仍停留在密码页,正在重新填写密码...', 'warn');
  646. await humanPause(450, 1100);
  647. fillInput(snapshot.passwordInput, password);
  648. }
  649. if (snapshot.submitButton && isActionEnabled(snapshot.submitButton)) {
  650. log(`步骤 4:页面仍停留在密码页,正在重新点击“继续”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  651. await humanPause(350, 900);
  652. simulateClick(snapshot.submitButton);
  653. await sleep(1200);
  654. continue;
  655. }
  656. log(`步骤 4:页面仍停留在密码页,但“继续”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  657. continue;
  658. }
  659. log(`步骤 4:页面仍在切换中,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  660. }
  661. throw new Error(`等待注册验证码页面就绪超时或自动恢复失败(已尝试 ${recoveryRound}/${maxRecoveryRounds} 轮)。URL: ${location.href}`);
  662. }
  663. async function waitForVerificationSubmitOutcome(step, timeout) {
  664. const resolvedTimeout = timeout ?? (step === 7 ? 30000 : 12000);
  665. const start = Date.now();
  666. while (Date.now() - start < resolvedTimeout) {
  667. throwIfStopped();
  668. const errorText = getVerificationErrorText();
  669. if (errorText) {
  670. return { invalidCode: true, errorText };
  671. }
  672. if (step === 4 && isStep5Ready()) {
  673. return { success: true };
  674. }
  675. if (step === 7 && isStep8Ready()) {
  676. return { success: true };
  677. }
  678. if (step === 7 && isAddPhonePageReady()) {
  679. return { success: true, addPhonePage: true };
  680. }
  681. await sleep(150);
  682. }
  683. if (isVerificationPageStillVisible()) {
  684. return {
  685. invalidCode: true,
  686. errorText: getVerificationErrorText() || '提交后仍停留在验证码页面,准备重新发送验证码。',
  687. };
  688. }
  689. return { success: true, assumed: true };
  690. }
  691. async function fillVerificationCode(step, payload) {
  692. const { code } = payload;
  693. if (!code) throw new Error('未提供验证码。');
  694. log(`步骤 ${step}:正在填写验证码:${code}`);
  695. if (step === 7) {
  696. const prepareResult = await prepareLoginCodeFlow();
  697. if (prepareResult?.restartFromStep6) {
  698. return prepareResult;
  699. }
  700. }
  701. // Find code input — could be a single input or multiple separate inputs
  702. let codeInput = null;
  703. try {
  704. codeInput = await waitForElement(VERIFICATION_CODE_INPUT_SELECTOR, 10000);
  705. } catch {
  706. // Check for multiple single-digit inputs (common pattern)
  707. const singleInputs = document.querySelectorAll('input[maxlength="1"]');
  708. if (singleInputs.length >= 6) {
  709. log(`步骤 ${step}:发现分开的单字符验证码输入框,正在逐个填写...`);
  710. for (let i = 0; i < 6 && i < singleInputs.length; i++) {
  711. fillInput(singleInputs[i], code[i]);
  712. await sleep(100);
  713. }
  714. const outcome = await waitForVerificationSubmitOutcome(step);
  715. if (outcome.invalidCode) {
  716. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  717. } else if (outcome.addPhonePage) {
  718. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  719. } else {
  720. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  721. }
  722. return outcome;
  723. }
  724. throw new Error('未找到验证码输入框。URL: ' + location.href);
  725. }
  726. fillInput(codeInput, code);
  727. log(`步骤 ${step}:验证码已填写`);
  728. // Report complete BEFORE submit (page may navigate away)
  729. // Submit
  730. await sleep(500);
  731. const submitBtn = document.querySelector('button[type="submit"]')
  732. || await waitForElementByText('button', /verify|confirm|submit|continue|确认|验证/i, 5000).catch(() => null);
  733. if (submitBtn) {
  734. await humanPause(450, 1200);
  735. simulateClick(submitBtn);
  736. log(`步骤 ${step}:验证码已提交`);
  737. }
  738. const outcome = await waitForVerificationSubmitOutcome(step);
  739. if (outcome.invalidCode) {
  740. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  741. } else if (outcome.addPhonePage) {
  742. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  743. } else {
  744. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  745. }
  746. return outcome;
  747. }
  748. // ============================================================
  749. // Step 6: Login with registered account (on OAuth auth page)
  750. // ============================================================
  751. async function step6_login(payload) {
  752. const { email, password } = payload;
  753. if (!email) throw new Error('登录时缺少邮箱地址。');
  754. log(`步骤 6:正在使用 ${email} 登录...`);
  755. // Wait for email input on the auth page
  756. let emailInput = null;
  757. try {
  758. emailInput = await waitForElement(
  759. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email" i], input[placeholder*="Email"]',
  760. 15000
  761. );
  762. } catch {
  763. throw new Error('在登录页未找到邮箱输入框。URL: ' + location.href);
  764. }
  765. await humanPause(500, 1400);
  766. fillInput(emailInput, email);
  767. log('步骤 6:邮箱已填写');
  768. // Submit email
  769. await sleep(500);
  770. const submitBtn1 = document.querySelector('button[type="submit"]')
  771. || await waitForElementByText('button', /continue|next|submit|继续|下一步/i, 5000).catch(() => null);
  772. if (submitBtn1) {
  773. await humanPause(400, 1100);
  774. simulateClick(submitBtn1);
  775. log('步骤 6:邮箱已提交');
  776. }
  777. await sleep(2000);
  778. // Check for password field
  779. const passwordInput = document.querySelector('input[type="password"]');
  780. if (passwordInput) {
  781. log('步骤 6:已找到密码输入框,正在填写密码...');
  782. await humanPause(550, 1450);
  783. fillInput(passwordInput, password);
  784. await sleep(500);
  785. const submitBtn2 = document.querySelector('button[type="submit"]')
  786. || await waitForElementByText('button', /continue|log\s*in|submit|sign\s*in|登录|继续/i, 5000).catch(() => null);
  787. // Report complete BEFORE submit in case page navigates
  788. reportComplete(6, { needsOTP: true });
  789. if (submitBtn2) {
  790. await humanPause(450, 1200);
  791. simulateClick(submitBtn2);
  792. log('步骤 6:密码已提交,可能还需要验证码(步骤 7)');
  793. }
  794. return;
  795. }
  796. // No password field — OTP flow
  797. log('步骤 6:未发现密码输入框,可能进入验证码流程或自动跳转。');
  798. reportComplete(6, { needsOTP: true });
  799. }
  800. // ============================================================
  801. // Step 8: Find "继续" on OAuth consent page for debugger click
  802. // ============================================================
  803. // After login + verification, page shows:
  804. // "使用 ChatGPT 登录到 Codex" with a "继续" submit button.
  805. // Background performs the actual click through the debugger Input API.
  806. async function step8_findAndClick() {
  807. log('步骤 8:正在查找 OAuth 同意页的“继续”按钮...');
  808. const continueBtn = await prepareStep8ContinueButton();
  809. const rect = getSerializableRect(continueBtn);
  810. log('步骤 8:已找到“继续”按钮并准备好调试器点击坐标。');
  811. return {
  812. rect,
  813. buttonText: (continueBtn.textContent || '').trim(),
  814. url: location.href,
  815. };
  816. }
  817. function getStep8State() {
  818. const pageText = getPageTextSnapshot();
  819. const continueBtn = getPrimaryContinueButton();
  820. const state = {
  821. url: location.href,
  822. consentPage: OAUTH_CONSENT_PAGE_PATTERN.test(pageText),
  823. consentReady: isStep8Ready(),
  824. verificationPage: isVerificationPageStillVisible(),
  825. addPhonePage: isAddPhonePageReady(),
  826. buttonFound: Boolean(continueBtn),
  827. buttonEnabled: isButtonEnabled(continueBtn),
  828. buttonText: continueBtn ? getActionText(continueBtn) : '',
  829. };
  830. if (continueBtn) {
  831. try {
  832. state.rect = getSerializableRect(continueBtn);
  833. } catch {
  834. state.rect = null;
  835. }
  836. }
  837. return state;
  838. }
  839. async function step8_triggerContinue(payload = {}) {
  840. const strategy = payload?.strategy || 'requestSubmit';
  841. const continueBtn = await prepareStep8ContinueButton({
  842. findTimeoutMs: payload?.findTimeoutMs,
  843. enabledTimeoutMs: payload?.enabledTimeoutMs,
  844. });
  845. const form = continueBtn.form || continueBtn.closest('form');
  846. switch (strategy) {
  847. case 'requestSubmit':
  848. if (!form || typeof form.requestSubmit !== 'function') {
  849. throw new Error('“继续”按钮当前不在可提交的 form 中,无法使用 requestSubmit。URL: ' + location.href);
  850. }
  851. form.requestSubmit(continueBtn);
  852. break;
  853. case 'nativeClick':
  854. continueBtn.click();
  855. break;
  856. case 'dispatchClick':
  857. simulateClick(continueBtn);
  858. break;
  859. default:
  860. throw new Error(`未知的 Step 8 触发策略:${strategy}`);
  861. }
  862. log(`Step 8: continue button triggered via ${strategy}.`);
  863. return {
  864. strategy,
  865. ...getStep8State(),
  866. };
  867. }
  868. async function prepareStep8ContinueButton(options = {}) {
  869. const {
  870. findTimeoutMs = 10000,
  871. enabledTimeoutMs = 8000,
  872. } = options;
  873. const continueBtn = await findContinueButton(findTimeoutMs);
  874. await waitForButtonEnabled(continueBtn, enabledTimeoutMs);
  875. await humanPause(250, 700);
  876. continueBtn.scrollIntoView({ behavior: 'auto', block: 'center' });
  877. continueBtn.focus();
  878. await waitForStableButtonRect(continueBtn);
  879. return continueBtn;
  880. }
  881. async function findContinueButton(timeout = 10000) {
  882. const start = Date.now();
  883. while (Date.now() - start < timeout) {
  884. throwIfStopped();
  885. if (isAddPhonePageReady()) {
  886. throw new Error('当前页面已进入手机号页面,不是 OAuth 授权同意页。URL: ' + location.href);
  887. }
  888. const button = getPrimaryContinueButton();
  889. if (button && isStep8Ready()) {
  890. return button;
  891. }
  892. await sleep(150);
  893. }
  894. throw new Error('在 OAuth 同意页未找到“继续”按钮,或页面尚未进入授权同意状态。URL: ' + location.href);
  895. }
  896. async function waitForButtonEnabled(button, timeout = 8000) {
  897. const start = Date.now();
  898. while (Date.now() - start < timeout) {
  899. throwIfStopped();
  900. if (isButtonEnabled(button)) return;
  901. await sleep(150);
  902. }
  903. throw new Error('“继续”按钮长时间不可点击。URL: ' + location.href);
  904. }
  905. function isButtonEnabled(button) {
  906. return Boolean(button)
  907. && !button.disabled
  908. && button.getAttribute('aria-disabled') !== 'true';
  909. }
  910. async function waitForStableButtonRect(button, timeout = 1500) {
  911. let previous = null;
  912. let stableSamples = 0;
  913. const start = Date.now();
  914. while (Date.now() - start < timeout) {
  915. throwIfStopped();
  916. const rect = button?.getBoundingClientRect?.();
  917. if (rect && rect.width > 0 && rect.height > 0) {
  918. const snapshot = {
  919. left: rect.left,
  920. top: rect.top,
  921. width: rect.width,
  922. height: rect.height,
  923. };
  924. if (
  925. previous
  926. && Math.abs(snapshot.left - previous.left) < 1
  927. && Math.abs(snapshot.top - previous.top) < 1
  928. && Math.abs(snapshot.width - previous.width) < 1
  929. && Math.abs(snapshot.height - previous.height) < 1
  930. ) {
  931. stableSamples += 1;
  932. if (stableSamples >= 2) {
  933. return;
  934. }
  935. } else {
  936. stableSamples = 0;
  937. }
  938. previous = snapshot;
  939. }
  940. await sleep(80);
  941. }
  942. }
  943. function getSerializableRect(el) {
  944. const rect = el.getBoundingClientRect();
  945. if (!rect.width || !rect.height) {
  946. throw new Error('滚动后“继续”按钮没有可点击尺寸。URL: ' + location.href);
  947. }
  948. return {
  949. left: rect.left,
  950. top: rect.top,
  951. width: rect.width,
  952. height: rect.height,
  953. centerX: rect.left + (rect.width / 2),
  954. centerY: rect.top + (rect.height / 2),
  955. };
  956. }
  957. // ============================================================
  958. // Step 5: Fill Name & Birthday / Age
  959. // ============================================================
  960. async function step5_fillNameBirthday(payload) {
  961. const { firstName, lastName, age, year, month, day } = payload;
  962. if (!firstName || !lastName) throw new Error('未提供姓名数据。');
  963. const resolvedAge = age ?? (year ? new Date().getFullYear() - Number(year) : null);
  964. const hasBirthdayData = [year, month, day].every(value => value != null && !Number.isNaN(Number(value)));
  965. if (!hasBirthdayData && (resolvedAge == null || Number.isNaN(Number(resolvedAge)))) {
  966. throw new Error('未提供生日或年龄数据。');
  967. }
  968. const fullName = `${firstName} ${lastName}`;
  969. log(`步骤 5:正在填写姓名:${fullName}`);
  970. // Actual DOM structure:
  971. // - Full name: <input name="name" placeholder="全名" type="text">
  972. // - Birthday: React Aria DateField or hidden input[name="birthday"]
  973. // - Age: <input name="age" type="text|number">
  974. // --- Full Name (single field, not first+last) ---
  975. let nameInput = null;
  976. try {
  977. nameInput = await waitForElement(
  978. 'input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]',
  979. 10000
  980. );
  981. } catch {
  982. throw new Error('未找到姓名输入框。URL: ' + location.href);
  983. }
  984. await humanPause(500, 1300);
  985. fillInput(nameInput, fullName);
  986. log(`步骤 5:姓名已填写:${fullName}`);
  987. let birthdayMode = false;
  988. let ageInput = null;
  989. let yearSpinner = null;
  990. let monthSpinner = null;
  991. let daySpinner = null;
  992. let hiddenBirthday = null;
  993. let yearReactSelect = null;
  994. let monthReactSelect = null;
  995. let dayReactSelect = null;
  996. let visibleAgeInput = false;
  997. let visibleBirthdaySpinners = false;
  998. let visibleBirthdaySelects = false;
  999. for (let i = 0; i < 100; i++) {
  1000. yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  1001. monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  1002. daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  1003. hiddenBirthday = document.querySelector('input[name="birthday"]');
  1004. ageInput = document.querySelector('input[name="age"]');
  1005. yearReactSelect = findBirthdayReactAriaSelect('年');
  1006. monthReactSelect = findBirthdayReactAriaSelect('月');
  1007. dayReactSelect = findBirthdayReactAriaSelect('天');
  1008. visibleAgeInput = Boolean(ageInput && isVisibleElement(ageInput));
  1009. visibleBirthdaySpinners = Boolean(
  1010. yearSpinner
  1011. && monthSpinner
  1012. && daySpinner
  1013. && isVisibleElement(yearSpinner)
  1014. && isVisibleElement(monthSpinner)
  1015. && isVisibleElement(daySpinner)
  1016. );
  1017. visibleBirthdaySelects = Boolean(
  1018. yearReactSelect?.button
  1019. && monthReactSelect?.button
  1020. && dayReactSelect?.button
  1021. && isVisibleElement(yearReactSelect.button)
  1022. && isVisibleElement(monthReactSelect.button)
  1023. && isVisibleElement(dayReactSelect.button)
  1024. );
  1025. if (visibleAgeInput) break;
  1026. if (visibleBirthdaySpinners || visibleBirthdaySelects) {
  1027. birthdayMode = true;
  1028. break;
  1029. }
  1030. await sleep(100);
  1031. }
  1032. if (birthdayMode) {
  1033. if (!hasBirthdayData) {
  1034. throw new Error('检测到生日字段,但未提供生日数据。');
  1035. }
  1036. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  1037. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  1038. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  1039. const yearReactSelect = findBirthdayReactAriaSelect('年');
  1040. const monthReactSelect = findBirthdayReactAriaSelect('月');
  1041. const dayReactSelect = findBirthdayReactAriaSelect('天');
  1042. if (yearReactSelect?.nativeSelect && monthReactSelect?.nativeSelect && dayReactSelect?.nativeSelect) {
  1043. const desiredDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1044. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1045. log('步骤 5:检测到 React Aria 下拉生日字段,正在填写生日...');
  1046. await humanPause(450, 1100);
  1047. await setReactAriaBirthdaySelect(yearReactSelect, year);
  1048. await humanPause(250, 650);
  1049. await setReactAriaBirthdaySelect(monthReactSelect, month);
  1050. await humanPause(250, 650);
  1051. await setReactAriaBirthdaySelect(dayReactSelect, day);
  1052. if (hiddenBirthday) {
  1053. const start = Date.now();
  1054. while (Date.now() - start < 2000) {
  1055. if ((hiddenBirthday.value || '') === desiredDate) break;
  1056. await sleep(100);
  1057. }
  1058. if ((hiddenBirthday.value || '') !== desiredDate) {
  1059. throw new Error(`生日值未成功写入页面。期望 ${desiredDate},实际 ${(hiddenBirthday.value || '空')}。`);
  1060. }
  1061. }
  1062. log(`步骤 5:React Aria 生日已填写:${desiredDate}`);
  1063. }
  1064. if (yearSpinner && monthSpinner && daySpinner) {
  1065. log('步骤 5:检测到生日字段,正在填写生日...');
  1066. async function setSpinButton(el, value) {
  1067. el.focus();
  1068. await sleep(100);
  1069. document.execCommand('selectAll', false, null);
  1070. await sleep(50);
  1071. const valueStr = String(value);
  1072. for (const char of valueStr) {
  1073. el.dispatchEvent(new KeyboardEvent('keydown', { key: char, code: `Digit${char}`, bubbles: true }));
  1074. el.dispatchEvent(new KeyboardEvent('keypress', { key: char, code: `Digit${char}`, bubbles: true }));
  1075. el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: char, bubbles: true }));
  1076. el.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: char, bubbles: true }));
  1077. await sleep(50);
  1078. }
  1079. el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab', code: 'Tab', bubbles: true }));
  1080. el.blur();
  1081. await sleep(100);
  1082. }
  1083. await humanPause(450, 1100);
  1084. await setSpinButton(yearSpinner, year);
  1085. await humanPause(250, 650);
  1086. await setSpinButton(monthSpinner, String(month).padStart(2, '0'));
  1087. await humanPause(250, 650);
  1088. await setSpinButton(daySpinner, String(day).padStart(2, '0'));
  1089. log(`步骤 5:生日已填写:${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
  1090. }
  1091. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1092. if (hiddenBirthday) {
  1093. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1094. hiddenBirthday.value = dateStr;
  1095. hiddenBirthday.dispatchEvent(new Event('input', { bubbles: true }));
  1096. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  1097. log(`步骤 5:已设置隐藏生日输入框:${dateStr}`);
  1098. }
  1099. } else if (ageInput) {
  1100. if (resolvedAge == null || Number.isNaN(Number(resolvedAge))) {
  1101. throw new Error('检测到年龄字段,但未提供年龄数据。');
  1102. }
  1103. await humanPause(500, 1300);
  1104. fillInput(ageInput, String(resolvedAge));
  1105. log(`步骤 5:年龄已填写:${resolvedAge}`);
  1106. } else {
  1107. throw new Error('未找到生日或年龄输入项。URL: ' + location.href);
  1108. }
  1109. // Click "完成帐户创建" button
  1110. await sleep(500);
  1111. const completeBtn = document.querySelector('button[type="submit"]')
  1112. || await waitForElementByText('button', /完成|create|continue|finish|done|agree/i, 5000).catch(() => null);
  1113. if (!completeBtn) {
  1114. throw new Error('未找到“完成帐户创建”按钮。URL: ' + location.href);
  1115. }
  1116. await humanPause(500, 1300);
  1117. simulateClick(completeBtn);
  1118. log('步骤 5:已点击“完成帐户创建”,正在等待页面结果...');
  1119. const outcome = await waitForStep5SubmitOutcome();
  1120. if (outcome.invalidProfile) {
  1121. throw new Error(`步骤 5:${outcome.errorText}`);
  1122. }
  1123. log(`步骤 5:资料已通过。`, 'ok');
  1124. reportComplete(5, { addPhonePage: Boolean(outcome.addPhonePage) });
  1125. }