signup-page.js 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  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 getStep7RestartFromStep6Signal() {
  553. if (!isLoginPage() || !matchesAuthTimeoutErrorPage(/\/log-in(?:[/?#]|$)/i)) {
  554. return null;
  555. }
  556. return {
  557. restartFromStep6: true,
  558. reason: 'login_timeout_error_page',
  559. url: location.href,
  560. };
  561. }
  562. function isSignupEmailAlreadyExistsPage() {
  563. return isSignupPasswordPage() && SIGNUP_EMAIL_EXISTS_PATTERN.test(getPageTextSnapshot());
  564. }
  565. function inspectSignupVerificationState() {
  566. if (isStep5Ready()) {
  567. return { state: 'step5' };
  568. }
  569. if (isVerificationPageStillVisible()) {
  570. return { state: 'verification' };
  571. }
  572. if (isSignupPasswordErrorPage()) {
  573. return {
  574. state: 'error',
  575. retryButton: getAuthRetryButton({ allowDisabled: true }),
  576. };
  577. }
  578. if (isSignupEmailAlreadyExistsPage()) {
  579. return { state: 'email_exists' };
  580. }
  581. const passwordInput = getSignupPasswordInput();
  582. if (passwordInput) {
  583. return {
  584. state: 'password',
  585. passwordInput,
  586. submitButton: getSignupPasswordSubmitButton({ allowDisabled: true }),
  587. };
  588. }
  589. return { state: 'unknown' };
  590. }
  591. async function waitForSignupVerificationTransition(timeout = 5000) {
  592. const start = Date.now();
  593. while (Date.now() - start < timeout) {
  594. throwIfStopped();
  595. const snapshot = inspectSignupVerificationState();
  596. if (snapshot.state === 'step5' || snapshot.state === 'verification' || snapshot.state === 'error' || snapshot.state === 'email_exists') {
  597. return snapshot;
  598. }
  599. await sleep(200);
  600. }
  601. return inspectSignupVerificationState();
  602. }
  603. async function prepareSignupVerificationFlow(payload = {}, timeout = 30000) {
  604. const { password } = payload;
  605. const start = Date.now();
  606. let recoveryRound = 0;
  607. const maxRecoveryRounds = 3;
  608. while (Date.now() - start < timeout && recoveryRound < maxRecoveryRounds) {
  609. throwIfStopped();
  610. const roundNo = recoveryRound + 1;
  611. log(`步骤 4:等待页面进入验证码阶段(第 ${roundNo}/${maxRecoveryRounds} 轮,先等待 5 秒)...`, 'info');
  612. const snapshot = await waitForSignupVerificationTransition(5000);
  613. if (snapshot.state === 'step5') {
  614. log('步骤 4:页面已进入验证码后的下一阶段,本步骤按已完成处理。', 'ok');
  615. return { ready: true, alreadyVerified: true, retried: recoveryRound };
  616. }
  617. if (snapshot.state === 'verification') {
  618. log(`步骤 4:验证码页面已就绪${recoveryRound ? `(期间自动恢复 ${recoveryRound} 次)` : ''}。`, 'ok');
  619. return { ready: true, retried: recoveryRound };
  620. }
  621. if (snapshot.state === 'email_exists') {
  622. throw new Error('当前邮箱已存在,需要重新开始新一轮。');
  623. }
  624. recoveryRound += 1;
  625. if (snapshot.state === 'error') {
  626. if (snapshot.retryButton && isActionEnabled(snapshot.retryButton)) {
  627. log(`步骤 4:检测到密码页超时报错,正在点击“重试”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  628. await humanPause(350, 900);
  629. simulateClick(snapshot.retryButton);
  630. await sleep(1200);
  631. continue;
  632. }
  633. log(`步骤 4:检测到异常页,但“重试”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  634. continue;
  635. }
  636. if (snapshot.state === 'password') {
  637. if (!password) {
  638. throw new Error('当前回到了密码页,但没有可用密码,无法自动重新提交。');
  639. }
  640. if ((snapshot.passwordInput.value || '') !== password) {
  641. log('步骤 4:页面仍停留在密码页,正在重新填写密码...', 'warn');
  642. await humanPause(450, 1100);
  643. fillInput(snapshot.passwordInput, password);
  644. }
  645. if (snapshot.submitButton && isActionEnabled(snapshot.submitButton)) {
  646. log(`步骤 4:页面仍停留在密码页,正在重新点击“继续”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  647. await humanPause(350, 900);
  648. simulateClick(snapshot.submitButton);
  649. await sleep(1200);
  650. continue;
  651. }
  652. log(`步骤 4:页面仍停留在密码页,但“继续”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  653. continue;
  654. }
  655. log(`步骤 4:页面仍在切换中,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  656. }
  657. throw new Error(`等待注册验证码页面就绪超时或自动恢复失败(已尝试 ${recoveryRound}/${maxRecoveryRounds} 轮)。URL: ${location.href}`);
  658. }
  659. async function waitForVerificationSubmitOutcome(step, timeout) {
  660. const resolvedTimeout = timeout ?? (step === 7 ? 30000 : 12000);
  661. const start = Date.now();
  662. while (Date.now() - start < resolvedTimeout) {
  663. throwIfStopped();
  664. const errorText = getVerificationErrorText();
  665. if (errorText) {
  666. return { invalidCode: true, errorText };
  667. }
  668. if (step === 4 && isStep5Ready()) {
  669. return { success: true };
  670. }
  671. if (step === 7 && isStep8Ready()) {
  672. return { success: true };
  673. }
  674. if (step === 7 && isAddPhonePageReady()) {
  675. return { success: true, addPhonePage: true };
  676. }
  677. await sleep(150);
  678. }
  679. if (isVerificationPageStillVisible()) {
  680. return {
  681. invalidCode: true,
  682. errorText: getVerificationErrorText() || '提交后仍停留在验证码页面,准备重新发送验证码。',
  683. };
  684. }
  685. return { success: true, assumed: true };
  686. }
  687. async function fillVerificationCode(step, payload) {
  688. const { code } = payload;
  689. if (!code) throw new Error('未提供验证码。');
  690. log(`步骤 ${step}:正在填写验证码:${code}`);
  691. if (step === 7) {
  692. const prepareResult = await prepareLoginCodeFlow();
  693. if (prepareResult?.restartFromStep6) {
  694. return prepareResult;
  695. }
  696. }
  697. // Find code input — could be a single input or multiple separate inputs
  698. let codeInput = null;
  699. try {
  700. codeInput = await waitForElement(VERIFICATION_CODE_INPUT_SELECTOR, 10000);
  701. } catch {
  702. // Check for multiple single-digit inputs (common pattern)
  703. const singleInputs = document.querySelectorAll('input[maxlength="1"]');
  704. if (singleInputs.length >= 6) {
  705. log(`步骤 ${step}:发现分开的单字符验证码输入框,正在逐个填写...`);
  706. for (let i = 0; i < 6 && i < singleInputs.length; i++) {
  707. fillInput(singleInputs[i], code[i]);
  708. await sleep(100);
  709. }
  710. const outcome = await waitForVerificationSubmitOutcome(step);
  711. if (outcome.invalidCode) {
  712. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  713. } else if (outcome.addPhonePage) {
  714. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  715. } else {
  716. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  717. }
  718. return outcome;
  719. }
  720. throw new Error('未找到验证码输入框。URL: ' + location.href);
  721. }
  722. fillInput(codeInput, code);
  723. log(`步骤 ${step}:验证码已填写`);
  724. // Report complete BEFORE submit (page may navigate away)
  725. // Submit
  726. await sleep(500);
  727. const submitBtn = document.querySelector('button[type="submit"]')
  728. || await waitForElementByText('button', /verify|confirm|submit|continue|确认|验证/i, 5000).catch(() => null);
  729. if (submitBtn) {
  730. await humanPause(450, 1200);
  731. simulateClick(submitBtn);
  732. log(`步骤 ${step}:验证码已提交`);
  733. }
  734. const outcome = await waitForVerificationSubmitOutcome(step);
  735. if (outcome.invalidCode) {
  736. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  737. } else if (outcome.addPhonePage) {
  738. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  739. } else {
  740. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  741. }
  742. return outcome;
  743. }
  744. // ============================================================
  745. // Step 6: Login with registered account (on OAuth auth page)
  746. // ============================================================
  747. async function step6_login(payload) {
  748. const { email, password } = payload;
  749. if (!email) throw new Error('登录时缺少邮箱地址。');
  750. log(`步骤 6:正在使用 ${email} 登录...`);
  751. // Wait for email input on the auth page
  752. let emailInput = null;
  753. try {
  754. emailInput = await waitForElement(
  755. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email" i], input[placeholder*="Email"]',
  756. 15000
  757. );
  758. } catch {
  759. throw new Error('在登录页未找到邮箱输入框。URL: ' + location.href);
  760. }
  761. await humanPause(500, 1400);
  762. fillInput(emailInput, email);
  763. log('步骤 6:邮箱已填写');
  764. // Submit email
  765. await sleep(500);
  766. const submitBtn1 = document.querySelector('button[type="submit"]')
  767. || await waitForElementByText('button', /continue|next|submit|继续|下一步/i, 5000).catch(() => null);
  768. if (submitBtn1) {
  769. await humanPause(400, 1100);
  770. simulateClick(submitBtn1);
  771. log('步骤 6:邮箱已提交');
  772. }
  773. await sleep(2000);
  774. // Check for password field
  775. const passwordInput = document.querySelector('input[type="password"]');
  776. if (passwordInput) {
  777. log('步骤 6:已找到密码输入框,正在填写密码...');
  778. await humanPause(550, 1450);
  779. fillInput(passwordInput, password);
  780. await sleep(500);
  781. const submitBtn2 = document.querySelector('button[type="submit"]')
  782. || await waitForElementByText('button', /continue|log\s*in|submit|sign\s*in|登录|继续/i, 5000).catch(() => null);
  783. // Report complete BEFORE submit in case page navigates
  784. reportComplete(6, { needsOTP: true });
  785. if (submitBtn2) {
  786. await humanPause(450, 1200);
  787. simulateClick(submitBtn2);
  788. log('步骤 6:密码已提交,可能还需要验证码(步骤 7)');
  789. }
  790. return;
  791. }
  792. // No password field — OTP flow
  793. log('步骤 6:未发现密码输入框,可能进入验证码流程或自动跳转。');
  794. reportComplete(6, { needsOTP: true });
  795. }
  796. // ============================================================
  797. // Step 8: Find "继续" on OAuth consent page for debugger click
  798. // ============================================================
  799. // After login + verification, page shows:
  800. // "使用 ChatGPT 登录到 Codex" with a "继续" submit button.
  801. // Background performs the actual click through the debugger Input API.
  802. async function step8_findAndClick() {
  803. log('步骤 8:正在查找 OAuth 同意页的“继续”按钮...');
  804. const continueBtn = await prepareStep8ContinueButton();
  805. const rect = getSerializableRect(continueBtn);
  806. log('步骤 8:已找到“继续”按钮并准备好调试器点击坐标。');
  807. return {
  808. rect,
  809. buttonText: (continueBtn.textContent || '').trim(),
  810. url: location.href,
  811. };
  812. }
  813. function getStep8State() {
  814. const pageText = getPageTextSnapshot();
  815. const continueBtn = getPrimaryContinueButton();
  816. const state = {
  817. url: location.href,
  818. consentPage: OAUTH_CONSENT_PAGE_PATTERN.test(pageText),
  819. consentReady: isStep8Ready(),
  820. verificationPage: isVerificationPageStillVisible(),
  821. addPhonePage: isAddPhonePageReady(),
  822. buttonFound: Boolean(continueBtn),
  823. buttonEnabled: isButtonEnabled(continueBtn),
  824. buttonText: continueBtn ? getActionText(continueBtn) : '',
  825. };
  826. if (continueBtn) {
  827. try {
  828. state.rect = getSerializableRect(continueBtn);
  829. } catch {
  830. state.rect = null;
  831. }
  832. }
  833. return state;
  834. }
  835. async function step8_triggerContinue(payload = {}) {
  836. const strategy = payload?.strategy || 'requestSubmit';
  837. const continueBtn = await prepareStep8ContinueButton({
  838. findTimeoutMs: payload?.findTimeoutMs,
  839. enabledTimeoutMs: payload?.enabledTimeoutMs,
  840. });
  841. const form = continueBtn.form || continueBtn.closest('form');
  842. switch (strategy) {
  843. case 'requestSubmit':
  844. if (!form || typeof form.requestSubmit !== 'function') {
  845. throw new Error('“继续”按钮当前不在可提交的 form 中,无法使用 requestSubmit。URL: ' + location.href);
  846. }
  847. form.requestSubmit(continueBtn);
  848. break;
  849. case 'nativeClick':
  850. continueBtn.click();
  851. break;
  852. case 'dispatchClick':
  853. simulateClick(continueBtn);
  854. break;
  855. default:
  856. throw new Error(`未知的 Step 8 触发策略:${strategy}`);
  857. }
  858. log(`Step 8: continue button triggered via ${strategy}.`);
  859. return {
  860. strategy,
  861. ...getStep8State(),
  862. };
  863. }
  864. async function prepareStep8ContinueButton(options = {}) {
  865. const {
  866. findTimeoutMs = 10000,
  867. enabledTimeoutMs = 8000,
  868. } = options;
  869. const continueBtn = await findContinueButton(findTimeoutMs);
  870. await waitForButtonEnabled(continueBtn, enabledTimeoutMs);
  871. await humanPause(250, 700);
  872. continueBtn.scrollIntoView({ behavior: 'auto', block: 'center' });
  873. continueBtn.focus();
  874. await waitForStableButtonRect(continueBtn);
  875. return continueBtn;
  876. }
  877. async function findContinueButton(timeout = 10000) {
  878. const start = Date.now();
  879. while (Date.now() - start < timeout) {
  880. throwIfStopped();
  881. if (isAddPhonePageReady()) {
  882. throw new Error('当前页面已进入手机号页面,不是 OAuth 授权同意页。URL: ' + location.href);
  883. }
  884. const button = getPrimaryContinueButton();
  885. if (button && isStep8Ready()) {
  886. return button;
  887. }
  888. await sleep(150);
  889. }
  890. throw new Error('在 OAuth 同意页未找到“继续”按钮,或页面尚未进入授权同意状态。URL: ' + location.href);
  891. }
  892. async function waitForButtonEnabled(button, timeout = 8000) {
  893. const start = Date.now();
  894. while (Date.now() - start < timeout) {
  895. throwIfStopped();
  896. if (isButtonEnabled(button)) return;
  897. await sleep(150);
  898. }
  899. throw new Error('“继续”按钮长时间不可点击。URL: ' + location.href);
  900. }
  901. function isButtonEnabled(button) {
  902. return Boolean(button)
  903. && !button.disabled
  904. && button.getAttribute('aria-disabled') !== 'true';
  905. }
  906. async function waitForStableButtonRect(button, timeout = 1500) {
  907. let previous = null;
  908. let stableSamples = 0;
  909. const start = Date.now();
  910. while (Date.now() - start < timeout) {
  911. throwIfStopped();
  912. const rect = button?.getBoundingClientRect?.();
  913. if (rect && rect.width > 0 && rect.height > 0) {
  914. const snapshot = {
  915. left: rect.left,
  916. top: rect.top,
  917. width: rect.width,
  918. height: rect.height,
  919. };
  920. if (
  921. previous
  922. && Math.abs(snapshot.left - previous.left) < 1
  923. && Math.abs(snapshot.top - previous.top) < 1
  924. && Math.abs(snapshot.width - previous.width) < 1
  925. && Math.abs(snapshot.height - previous.height) < 1
  926. ) {
  927. stableSamples += 1;
  928. if (stableSamples >= 2) {
  929. return;
  930. }
  931. } else {
  932. stableSamples = 0;
  933. }
  934. previous = snapshot;
  935. }
  936. await sleep(80);
  937. }
  938. }
  939. function getSerializableRect(el) {
  940. const rect = el.getBoundingClientRect();
  941. if (!rect.width || !rect.height) {
  942. throw new Error('滚动后“继续”按钮没有可点击尺寸。URL: ' + location.href);
  943. }
  944. return {
  945. left: rect.left,
  946. top: rect.top,
  947. width: rect.width,
  948. height: rect.height,
  949. centerX: rect.left + (rect.width / 2),
  950. centerY: rect.top + (rect.height / 2),
  951. };
  952. }
  953. // ============================================================
  954. // Step 5: Fill Name & Birthday / Age
  955. // ============================================================
  956. async function step5_fillNameBirthday(payload) {
  957. const { firstName, lastName, age, year, month, day } = payload;
  958. if (!firstName || !lastName) throw new Error('未提供姓名数据。');
  959. const resolvedAge = age ?? (year ? new Date().getFullYear() - Number(year) : null);
  960. const hasBirthdayData = [year, month, day].every(value => value != null && !Number.isNaN(Number(value)));
  961. if (!hasBirthdayData && (resolvedAge == null || Number.isNaN(Number(resolvedAge)))) {
  962. throw new Error('未提供生日或年龄数据。');
  963. }
  964. const fullName = `${firstName} ${lastName}`;
  965. log(`步骤 5:正在填写姓名:${fullName}`);
  966. // Actual DOM structure:
  967. // - Full name: <input name="name" placeholder="全名" type="text">
  968. // - Birthday: React Aria DateField or hidden input[name="birthday"]
  969. // - Age: <input name="age" type="text|number">
  970. // --- Full Name (single field, not first+last) ---
  971. let nameInput = null;
  972. try {
  973. nameInput = await waitForElement(
  974. 'input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]',
  975. 10000
  976. );
  977. } catch {
  978. throw new Error('未找到姓名输入框。URL: ' + location.href);
  979. }
  980. await humanPause(500, 1300);
  981. fillInput(nameInput, fullName);
  982. log(`步骤 5:姓名已填写:${fullName}`);
  983. let birthdayMode = false;
  984. let ageInput = null;
  985. let yearSpinner = null;
  986. let monthSpinner = null;
  987. let daySpinner = null;
  988. let hiddenBirthday = null;
  989. let yearReactSelect = null;
  990. let monthReactSelect = null;
  991. let dayReactSelect = null;
  992. let visibleAgeInput = false;
  993. let visibleBirthdaySpinners = false;
  994. let visibleBirthdaySelects = false;
  995. for (let i = 0; i < 100; i++) {
  996. yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  997. monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  998. daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  999. hiddenBirthday = document.querySelector('input[name="birthday"]');
  1000. ageInput = document.querySelector('input[name="age"]');
  1001. yearReactSelect = findBirthdayReactAriaSelect('年');
  1002. monthReactSelect = findBirthdayReactAriaSelect('月');
  1003. dayReactSelect = findBirthdayReactAriaSelect('天');
  1004. visibleAgeInput = Boolean(ageInput && isVisibleElement(ageInput));
  1005. visibleBirthdaySpinners = Boolean(
  1006. yearSpinner
  1007. && monthSpinner
  1008. && daySpinner
  1009. && isVisibleElement(yearSpinner)
  1010. && isVisibleElement(monthSpinner)
  1011. && isVisibleElement(daySpinner)
  1012. );
  1013. visibleBirthdaySelects = Boolean(
  1014. yearReactSelect?.button
  1015. && monthReactSelect?.button
  1016. && dayReactSelect?.button
  1017. && isVisibleElement(yearReactSelect.button)
  1018. && isVisibleElement(monthReactSelect.button)
  1019. && isVisibleElement(dayReactSelect.button)
  1020. );
  1021. if (visibleAgeInput) break;
  1022. if (visibleBirthdaySpinners || visibleBirthdaySelects) {
  1023. birthdayMode = true;
  1024. break;
  1025. }
  1026. await sleep(100);
  1027. }
  1028. if (birthdayMode) {
  1029. if (!hasBirthdayData) {
  1030. throw new Error('检测到生日字段,但未提供生日数据。');
  1031. }
  1032. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  1033. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  1034. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  1035. const yearReactSelect = findBirthdayReactAriaSelect('年');
  1036. const monthReactSelect = findBirthdayReactAriaSelect('月');
  1037. const dayReactSelect = findBirthdayReactAriaSelect('天');
  1038. if (yearReactSelect?.nativeSelect && monthReactSelect?.nativeSelect && dayReactSelect?.nativeSelect) {
  1039. const desiredDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1040. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1041. log('步骤 5:检测到 React Aria 下拉生日字段,正在填写生日...');
  1042. await humanPause(450, 1100);
  1043. await setReactAriaBirthdaySelect(yearReactSelect, year);
  1044. await humanPause(250, 650);
  1045. await setReactAriaBirthdaySelect(monthReactSelect, month);
  1046. await humanPause(250, 650);
  1047. await setReactAriaBirthdaySelect(dayReactSelect, day);
  1048. if (hiddenBirthday) {
  1049. const start = Date.now();
  1050. while (Date.now() - start < 2000) {
  1051. if ((hiddenBirthday.value || '') === desiredDate) break;
  1052. await sleep(100);
  1053. }
  1054. if ((hiddenBirthday.value || '') !== desiredDate) {
  1055. throw new Error(`生日值未成功写入页面。期望 ${desiredDate},实际 ${(hiddenBirthday.value || '空')}。`);
  1056. }
  1057. }
  1058. log(`步骤 5:React Aria 生日已填写:${desiredDate}`);
  1059. }
  1060. if (yearSpinner && monthSpinner && daySpinner) {
  1061. log('步骤 5:检测到生日字段,正在填写生日...');
  1062. async function setSpinButton(el, value) {
  1063. el.focus();
  1064. await sleep(100);
  1065. document.execCommand('selectAll', false, null);
  1066. await sleep(50);
  1067. const valueStr = String(value);
  1068. for (const char of valueStr) {
  1069. el.dispatchEvent(new KeyboardEvent('keydown', { key: char, code: `Digit${char}`, bubbles: true }));
  1070. el.dispatchEvent(new KeyboardEvent('keypress', { key: char, code: `Digit${char}`, bubbles: true }));
  1071. el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: char, bubbles: true }));
  1072. el.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: char, bubbles: true }));
  1073. await sleep(50);
  1074. }
  1075. el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab', code: 'Tab', bubbles: true }));
  1076. el.blur();
  1077. await sleep(100);
  1078. }
  1079. await humanPause(450, 1100);
  1080. await setSpinButton(yearSpinner, year);
  1081. await humanPause(250, 650);
  1082. await setSpinButton(monthSpinner, String(month).padStart(2, '0'));
  1083. await humanPause(250, 650);
  1084. await setSpinButton(daySpinner, String(day).padStart(2, '0'));
  1085. log(`步骤 5:生日已填写:${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
  1086. }
  1087. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1088. if (hiddenBirthday) {
  1089. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1090. hiddenBirthday.value = dateStr;
  1091. hiddenBirthday.dispatchEvent(new Event('input', { bubbles: true }));
  1092. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  1093. log(`步骤 5:已设置隐藏生日输入框:${dateStr}`);
  1094. }
  1095. } else if (ageInput) {
  1096. if (resolvedAge == null || Number.isNaN(Number(resolvedAge))) {
  1097. throw new Error('检测到年龄字段,但未提供年龄数据。');
  1098. }
  1099. await humanPause(500, 1300);
  1100. fillInput(ageInput, String(resolvedAge));
  1101. log(`步骤 5:年龄已填写:${resolvedAge}`);
  1102. } else {
  1103. throw new Error('未找到生日或年龄输入项。URL: ' + location.href);
  1104. }
  1105. // Click "完成帐户创建" button
  1106. await sleep(500);
  1107. const completeBtn = document.querySelector('button[type="submit"]')
  1108. || await waitForElementByText('button', /完成|create|continue|finish|done|agree/i, 5000).catch(() => null);
  1109. if (!completeBtn) {
  1110. throw new Error('未找到“完成帐户创建”按钮。URL: ' + location.href);
  1111. }
  1112. await humanPause(500, 1300);
  1113. simulateClick(completeBtn);
  1114. log('步骤 5:已点击“完成帐户创建”,正在等待页面结果...');
  1115. const outcome = await waitForStep5SubmitOutcome();
  1116. if (outcome.invalidProfile) {
  1117. throw new Error(`步骤 5:${outcome.errorText}`);
  1118. }
  1119. log(`步骤 5:资料已通过。`, 'ok');
  1120. reportComplete(5, { addPhonePage: Boolean(outcome.addPhonePage) });
  1121. }