signup-page.js 43 KB

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