signup-page.js 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852
  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 === 'GET_LOGIN_AUTH_STATE'
  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 'GET_LOGIN_AUTH_STATE':
  51. return serializeLoginAuthState(inspectLoginAuthState());
  52. case 'PREPARE_SIGNUP_VERIFICATION':
  53. return await prepareSignupVerificationFlow(message.payload);
  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 resendVerificationCode(step, timeout = 45000) {
  155. if (step === 7) {
  156. await waitForLoginVerificationPageReady();
  157. }
  158. const start = Date.now();
  159. let action = null;
  160. let loggedWaiting = false;
  161. while (Date.now() - start < timeout) {
  162. throwIfStopped();
  163. action = findResendVerificationCodeTrigger({ allowDisabled: true });
  164. if (action && isActionEnabled(action)) {
  165. log(`步骤 ${step}:重新发送验证码按钮已可用。`);
  166. await humanPause(350, 900);
  167. simulateClick(action);
  168. await sleep(1200);
  169. return {
  170. resent: true,
  171. buttonText: getActionText(action),
  172. };
  173. }
  174. if (action && !loggedWaiting) {
  175. loggedWaiting = true;
  176. log(`步骤 ${step}:正在等待重新发送验证码按钮变为可点击...`);
  177. }
  178. await sleep(250);
  179. }
  180. throw new Error('无法点击重新发送验证码按钮。URL: ' + location.href);
  181. }
  182. // ============================================================
  183. // Step 2: Click Register
  184. // ============================================================
  185. async function step2_clickRegister() {
  186. log('步骤 2:正在查找注册按钮...');
  187. let registerBtn = null;
  188. try {
  189. registerBtn = await waitForElementByText(
  190. 'a, button, [role="button"], [role="link"]',
  191. /sign\s*up|register|create\s*account|注册/i,
  192. 10000
  193. );
  194. } catch {
  195. // Some pages may have a direct link
  196. try {
  197. registerBtn = await waitForElement('a[href*="signup"], a[href*="register"]', 5000);
  198. } catch {
  199. throw new Error(
  200. '未找到注册按钮。' +
  201. '请在 DevTools 中检查认证页面 DOM。URL: ' + location.href
  202. );
  203. }
  204. }
  205. await humanPause(450, 1200);
  206. reportComplete(2);
  207. simulateClick(registerBtn);
  208. log('步骤 2:已点击注册按钮');
  209. }
  210. // ============================================================
  211. // Step 3: Fill Email & Password
  212. // ============================================================
  213. async function step3_fillEmailPassword(payload) {
  214. const { email } = payload;
  215. if (!email) throw new Error('未提供邮箱地址,请先在侧边栏粘贴邮箱。');
  216. log(`步骤 3:正在填写邮箱:${email}`);
  217. // Find email input
  218. let emailInput = null;
  219. try {
  220. emailInput = await waitForElement(
  221. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email"], input[placeholder*="Email"]',
  222. 10000
  223. );
  224. } catch {
  225. throw new Error('在注册页未找到邮箱输入框。URL: ' + location.href);
  226. }
  227. await humanPause(500, 1400);
  228. fillInput(emailInput, email);
  229. log('步骤 3:邮箱已填写');
  230. // Check if password field is on the same page
  231. let passwordInput = document.querySelector('input[type="password"]');
  232. if (!passwordInput) {
  233. // Need to submit email first to get to password page
  234. log('步骤 3:暂未发现密码输入框,先提交邮箱...');
  235. const submitBtn = document.querySelector('button[type="submit"]')
  236. || await waitForElementByText('button', /continue|next|submit|继续|下一步/i, 5000).catch(() => null);
  237. if (submitBtn) {
  238. await humanPause(400, 1100);
  239. simulateClick(submitBtn);
  240. log('步骤 3:邮箱已提交,正在等待密码输入框...');
  241. await sleep(2000);
  242. }
  243. try {
  244. passwordInput = await waitForElement('input[type="password"]', 10000);
  245. } catch {
  246. throw new Error('提交邮箱后仍未找到密码输入框。URL: ' + location.href);
  247. }
  248. }
  249. if (!payload.password) throw new Error('未提供密码,步骤 3 需要可用密码。');
  250. await humanPause(600, 1500);
  251. fillInput(passwordInput, payload.password);
  252. log('步骤 3:密码已填写');
  253. const submitBtn = document.querySelector('button[type="submit"]')
  254. || await waitForElementByText('button', /continue|sign\s*up|submit|注册|创建|create/i, 5000).catch(() => null);
  255. // Report complete BEFORE submit, because submit causes page navigation
  256. // which kills the content script connection
  257. const signupVerificationRequestedAt = submitBtn ? Date.now() : null;
  258. reportComplete(3, { email, signupVerificationRequestedAt });
  259. // Submit the form (page will navigate away after this)
  260. await sleep(500);
  261. if (submitBtn) {
  262. await humanPause(500, 1300);
  263. simulateClick(submitBtn);
  264. log('步骤 3:表单已提交');
  265. }
  266. }
  267. // ============================================================
  268. // Fill Verification Code (used by step 4 and step 7)
  269. // ============================================================
  270. const INVALID_VERIFICATION_CODE_PATTERN = /代码不正确|验证码不正确|验证码错误|code\s+(?:is\s+)?incorrect|invalid\s+code|incorrect\s+code|try\s+again/i;
  271. const VERIFICATION_PAGE_PATTERN = /检查您的收件箱|输入我们刚刚向|重新发送电子邮件|重新发送验证码|代码不正确|email\s+verification|check\s+your\s+inbox|enter\s+the\s+code|we\s+just\s+sent|we\s+emailed|resend/i;
  272. const OAUTH_CONSENT_PAGE_PATTERN = /使用\s*ChatGPT\s*登录到\s*Codex|sign\s+in\s+to\s+codex(?:\s+with\s+chatgpt)?|login\s+to\s+codex|log\s+in\s+to\s+codex|authorize|授权/i;
  273. const OAUTH_CONSENT_FORM_SELECTOR = 'form[action*="/sign-in-with-chatgpt/" i][action*="/consent" i]';
  274. const CONTINUE_ACTION_PATTERN = /继续|continue/i;
  275. const ADD_PHONE_PAGE_PATTERN = /add[\s-]*phone|添加手机号|手机号码|手机号|phone\s+number|telephone/i;
  276. 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;
  277. const AUTH_TIMEOUT_ERROR_TITLE_PATTERN = /糟糕,出错了|something\s+went\s+wrong|oops/i;
  278. const AUTH_TIMEOUT_ERROR_DETAIL_PATTERN = /operation\s+timed\s+out|timed\s+out|请求超时|操作超时/i;
  279. 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;
  280. function getVerificationErrorText() {
  281. const messages = [];
  282. const selectors = [
  283. '.react-aria-FieldError',
  284. '[slot="errorMessage"]',
  285. '[id$="-error"]',
  286. '[data-invalid="true"] + *',
  287. '[aria-invalid="true"] + *',
  288. '[class*="error"]',
  289. ];
  290. for (const selector of selectors) {
  291. document.querySelectorAll(selector).forEach((el) => {
  292. const text = (el.textContent || '').replace(/\s+/g, ' ').trim();
  293. if (text) {
  294. messages.push(text);
  295. }
  296. });
  297. }
  298. const invalidInput = document.querySelector(`${VERIFICATION_CODE_INPUT_SELECTOR}[aria-invalid="true"], ${VERIFICATION_CODE_INPUT_SELECTOR}[data-invalid="true"]`);
  299. if (invalidInput) {
  300. const wrapper = invalidInput.closest('form, [data-rac], ._root_18qcl_51, div');
  301. if (wrapper) {
  302. const text = (wrapper.textContent || '').replace(/\s+/g, ' ').trim();
  303. if (text) {
  304. messages.push(text);
  305. }
  306. }
  307. }
  308. return messages.find((text) => INVALID_VERIFICATION_CODE_PATTERN.test(text)) || '';
  309. }
  310. function isStep5Ready() {
  311. return Boolean(
  312. document.querySelector('input[name="name"], input[autocomplete="name"], input[name="birthday"], input[name="age"], [role="spinbutton"][data-type="year"]')
  313. );
  314. }
  315. function getPageTextSnapshot() {
  316. return (document.body?.innerText || document.body?.textContent || '')
  317. .replace(/\s+/g, ' ')
  318. .trim();
  319. }
  320. function getOAuthConsentForm() {
  321. return document.querySelector(OAUTH_CONSENT_FORM_SELECTOR);
  322. }
  323. function getPrimaryContinueButton() {
  324. const consentForm = getOAuthConsentForm();
  325. if (consentForm) {
  326. const formButtons = Array.from(
  327. consentForm.querySelectorAll('button[type="submit"], input[type="submit"], [role="button"]')
  328. );
  329. const formContinueButton = formButtons.find((el) => {
  330. if (!isVisibleElement(el)) return false;
  331. const ddActionName = el.getAttribute?.('data-dd-action-name') || '';
  332. return ddActionName === 'Continue' || CONTINUE_ACTION_PATTERN.test(getActionText(el));
  333. });
  334. if (formContinueButton) {
  335. return formContinueButton;
  336. }
  337. const firstVisibleSubmit = formButtons.find(isVisibleElement);
  338. if (firstVisibleSubmit) {
  339. return firstVisibleSubmit;
  340. }
  341. }
  342. const continueBtn = document.querySelector(
  343. `${OAUTH_CONSENT_FORM_SELECTOR} button[type="submit"], button[type="submit"][data-dd-action-name="Continue"], button[type="submit"]._primary_3rdp0_107`
  344. );
  345. if (continueBtn && isVisibleElement(continueBtn)) {
  346. return continueBtn;
  347. }
  348. const buttons = document.querySelectorAll('button, [role="button"]');
  349. return Array.from(buttons).find((el) => {
  350. if (!isVisibleElement(el)) return false;
  351. const ddActionName = el.getAttribute?.('data-dd-action-name') || '';
  352. return ddActionName === 'Continue' || CONTINUE_ACTION_PATTERN.test(getActionText(el));
  353. }) || null;
  354. }
  355. function isOAuthConsentPage() {
  356. const pageText = getPageTextSnapshot();
  357. if (OAUTH_CONSENT_PAGE_PATTERN.test(pageText)) {
  358. return true;
  359. }
  360. if (getOAuthConsentForm()) {
  361. return true;
  362. }
  363. return /\bcodex\b/i.test(pageText) && /\bchatgpt\b/i.test(pageText) && Boolean(getPrimaryContinueButton());
  364. }
  365. function isVerificationPageStillVisible() {
  366. if (getVerificationCodeTarget()) return true;
  367. if (findResendVerificationCodeTrigger({ allowDisabled: true })) return true;
  368. if (document.querySelector('form[action*="email-verification" i]')) return true;
  369. return VERIFICATION_PAGE_PATTERN.test(getPageTextSnapshot());
  370. }
  371. function isAddPhonePageReady() {
  372. const path = `${location.pathname || ''} ${location.href || ''}`;
  373. if (/\/add-phone(?:[/?#]|$)/i.test(path)) return true;
  374. const phoneInput = document.querySelector(
  375. 'input[type="tel"]:not([maxlength="6"]), input[name*="phone" i], input[id*="phone" i], input[autocomplete="tel"]'
  376. );
  377. if (phoneInput && isVisibleElement(phoneInput)) {
  378. return true;
  379. }
  380. return ADD_PHONE_PAGE_PATTERN.test(getPageTextSnapshot());
  381. }
  382. function isStep8Ready() {
  383. const continueBtn = getPrimaryContinueButton();
  384. if (!continueBtn) return false;
  385. if (isVerificationPageStillVisible()) return false;
  386. if (isAddPhonePageReady()) return false;
  387. return isOAuthConsentPage();
  388. }
  389. function normalizeInlineText(text) {
  390. return (text || '').replace(/\s+/g, ' ').trim();
  391. }
  392. function findBirthdayReactAriaSelect(labelText) {
  393. const normalizedLabel = normalizeInlineText(labelText);
  394. const roots = document.querySelectorAll('.react-aria-Select');
  395. for (const root of roots) {
  396. const labelEl = Array.from(root.querySelectorAll('span')).find((el) => normalizeInlineText(el.textContent) === normalizedLabel);
  397. if (!labelEl) continue;
  398. const item = root.closest('[class*="selectItem"], ._selectItem_ppsls_113') || root.parentElement;
  399. const nativeSelect = item?.querySelector('[data-testid="hidden-select-container"] select') || null;
  400. const button = root.querySelector('button[aria-haspopup="listbox"]') || null;
  401. const valueEl = root.querySelector('.react-aria-SelectValue') || null;
  402. return { root, item, labelEl, nativeSelect, button, valueEl };
  403. }
  404. return null;
  405. }
  406. async function setReactAriaBirthdaySelect(control, value) {
  407. if (!control?.nativeSelect) {
  408. throw new Error('未找到可写入的生日下拉框。');
  409. }
  410. const desiredValue = String(value);
  411. const option = Array.from(control.nativeSelect.options).find((item) => item.value === desiredValue);
  412. if (!option) {
  413. throw new Error(`生日下拉框中不存在值 ${desiredValue}。`);
  414. }
  415. control.nativeSelect.value = desiredValue;
  416. option.selected = true;
  417. control.nativeSelect.dispatchEvent(new Event('input', { bubbles: true }));
  418. control.nativeSelect.dispatchEvent(new Event('change', { bubbles: true }));
  419. await sleep(120);
  420. }
  421. function getStep5ErrorText() {
  422. const messages = [];
  423. const selectors = [
  424. '.react-aria-FieldError',
  425. '[slot="errorMessage"]',
  426. '[id$="-error"]',
  427. '[id$="-errors"]',
  428. '[role="alert"]',
  429. '[aria-live="assertive"]',
  430. '[aria-live="polite"]',
  431. '[class*="error"]',
  432. ];
  433. for (const selector of selectors) {
  434. document.querySelectorAll(selector).forEach((el) => {
  435. if (!isVisibleElement(el)) return;
  436. const text = normalizeInlineText(el.textContent);
  437. if (text) {
  438. messages.push(text);
  439. }
  440. });
  441. }
  442. const invalidField = Array.from(document.querySelectorAll('[aria-invalid="true"], [data-invalid="true"]'))
  443. .find((el) => isVisibleElement(el));
  444. if (invalidField) {
  445. const wrapper = invalidField.closest('form, fieldset, [data-rac], div');
  446. if (wrapper) {
  447. const text = normalizeInlineText(wrapper.textContent);
  448. if (text) {
  449. messages.push(text);
  450. }
  451. }
  452. }
  453. return messages.find((text) => STEP5_SUBMIT_ERROR_PATTERN.test(text)) || '';
  454. }
  455. async function waitForStep5SubmitOutcome(timeout = 15000) {
  456. const start = Date.now();
  457. while (Date.now() - start < timeout) {
  458. throwIfStopped();
  459. const errorText = getStep5ErrorText();
  460. if (errorText) {
  461. return { invalidProfile: true, errorText };
  462. }
  463. if (isAddPhonePageReady()) {
  464. return { success: true, addPhonePage: true };
  465. }
  466. if (isStep8Ready()) {
  467. return { success: true };
  468. }
  469. await sleep(150);
  470. }
  471. const errorText = getStep5ErrorText();
  472. if (errorText) {
  473. return { invalidProfile: true, errorText };
  474. }
  475. return {
  476. invalidProfile: true,
  477. errorText: '提交后未进入下一阶段,请检查生日是否真正被页面接受。',
  478. };
  479. }
  480. function isSignupPasswordPage() {
  481. return /\/create-account\/password(?:[/?#]|$)/i.test(location.pathname || '');
  482. }
  483. function getSignupPasswordInput() {
  484. const input = document.querySelector('input[type="password"]');
  485. return input && isVisibleElement(input) ? input : null;
  486. }
  487. function getSignupPasswordSubmitButton({ allowDisabled = false } = {}) {
  488. const direct = document.querySelector('button[type="submit"]');
  489. if (direct && isVisibleElement(direct) && (allowDisabled || isActionEnabled(direct))) {
  490. return direct;
  491. }
  492. const candidates = document.querySelectorAll('button, [role="button"]');
  493. return Array.from(candidates).find((el) => {
  494. if (!isVisibleElement(el) || (!allowDisabled && !isActionEnabled(el))) return false;
  495. const text = getActionText(el);
  496. return /继续|continue|submit|创建|create/i.test(text);
  497. }) || null;
  498. }
  499. function getAuthRetryButton({ allowDisabled = false } = {}) {
  500. const direct = document.querySelector('button[data-dd-action-name="Try again"]');
  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 /重试|try\s+again/i.test(text);
  509. }) || null;
  510. }
  511. function getAuthTimeoutErrorPageState(options = {}) {
  512. const { pathPatterns = [] } = options;
  513. const path = location.pathname || '';
  514. if (pathPatterns.length && !pathPatterns.some((pattern) => pattern.test(path))) {
  515. return null;
  516. }
  517. const retryButton = getAuthRetryButton({ allowDisabled: true });
  518. if (!retryButton) {
  519. return null;
  520. }
  521. const text = getPageTextSnapshot();
  522. const titleMatched = AUTH_TIMEOUT_ERROR_TITLE_PATTERN.test(text)
  523. || AUTH_TIMEOUT_ERROR_TITLE_PATTERN.test(document.title || '');
  524. const detailMatched = AUTH_TIMEOUT_ERROR_DETAIL_PATTERN.test(text);
  525. if (!titleMatched && !detailMatched) {
  526. return null;
  527. }
  528. return {
  529. path,
  530. url: location.href,
  531. retryButton,
  532. retryEnabled: isActionEnabled(retryButton),
  533. titleMatched,
  534. detailMatched,
  535. };
  536. }
  537. function getSignupPasswordTimeoutErrorPageState() {
  538. return getAuthTimeoutErrorPageState({
  539. pathPatterns: [/\/create-account\/password(?:[/?#]|$)/i],
  540. });
  541. }
  542. function getLoginTimeoutErrorPageState() {
  543. return getAuthTimeoutErrorPageState({
  544. pathPatterns: [/\/log-in(?:[/?#]|$)/i],
  545. });
  546. }
  547. function getLoginEmailInput() {
  548. const input = document.querySelector(
  549. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email" i], input[placeholder*="Email"]'
  550. );
  551. return input && isVisibleElement(input) ? input : null;
  552. }
  553. function getLoginPasswordInput() {
  554. const input = document.querySelector('input[type="password"]');
  555. return input && isVisibleElement(input) ? input : null;
  556. }
  557. function getLoginSubmitButton({ allowDisabled = false } = {}) {
  558. const direct = document.querySelector('button[type="submit"], input[type="submit"]');
  559. if (direct && isVisibleElement(direct) && (allowDisabled || isActionEnabled(direct))) {
  560. return direct;
  561. }
  562. const candidates = document.querySelectorAll(
  563. 'button, a, [role="button"], [role="link"], input[type="button"], input[type="submit"]'
  564. );
  565. return Array.from(candidates).find((el) => {
  566. if (!isVisibleElement(el) || (!allowDisabled && !isActionEnabled(el))) return false;
  567. const text = getActionText(el);
  568. if (!text || ONE_TIME_CODE_LOGIN_PATTERN.test(text)) return false;
  569. return /continue|next|submit|sign\s*in|log\s*in|继续|下一步|登录/i.test(text);
  570. }) || null;
  571. }
  572. function inspectLoginAuthState() {
  573. const retryState = getLoginTimeoutErrorPageState();
  574. const verificationTarget = getVerificationCodeTarget();
  575. const passwordInput = getLoginPasswordInput();
  576. const emailInput = getLoginEmailInput();
  577. const switchTrigger = findOneTimeCodeLoginTrigger();
  578. const submitButton = getLoginSubmitButton({ allowDisabled: true });
  579. const verificationVisible = isVerificationPageStillVisible();
  580. const addPhonePage = isAddPhonePageReady();
  581. const consentReady = isStep8Ready();
  582. const oauthConsentPage = isOAuthConsentPage();
  583. const baseState = {
  584. state: 'unknown',
  585. url: location.href,
  586. path: location.pathname || '',
  587. retryButton: retryState?.retryButton || null,
  588. retryEnabled: Boolean(retryState?.retryEnabled),
  589. titleMatched: Boolean(retryState?.titleMatched),
  590. detailMatched: Boolean(retryState?.detailMatched),
  591. verificationTarget,
  592. passwordInput,
  593. emailInput,
  594. submitButton,
  595. switchTrigger,
  596. verificationVisible,
  597. addPhonePage,
  598. oauthConsentPage,
  599. consentReady,
  600. };
  601. if (verificationTarget) {
  602. return {
  603. ...baseState,
  604. state: 'verification_page',
  605. };
  606. }
  607. if (retryState) {
  608. return {
  609. ...baseState,
  610. state: 'login_timeout_error_page',
  611. };
  612. }
  613. if (addPhonePage) {
  614. return {
  615. ...baseState,
  616. state: 'add_phone_page',
  617. };
  618. }
  619. if (oauthConsentPage) {
  620. return {
  621. ...baseState,
  622. state: 'oauth_consent_page',
  623. };
  624. }
  625. if (passwordInput || switchTrigger) {
  626. return {
  627. ...baseState,
  628. state: 'password_page',
  629. };
  630. }
  631. if (emailInput) {
  632. return {
  633. ...baseState,
  634. state: 'email_page',
  635. };
  636. }
  637. if (verificationVisible) {
  638. return {
  639. ...baseState,
  640. state: 'verification_page',
  641. };
  642. }
  643. return baseState;
  644. }
  645. function serializeLoginAuthState(snapshot) {
  646. return {
  647. state: snapshot?.state || 'unknown',
  648. url: snapshot?.url || location.href,
  649. path: snapshot?.path || location.pathname || '',
  650. retryEnabled: Boolean(snapshot?.retryEnabled),
  651. titleMatched: Boolean(snapshot?.titleMatched),
  652. detailMatched: Boolean(snapshot?.detailMatched),
  653. hasVerificationTarget: Boolean(snapshot?.verificationTarget),
  654. hasPasswordInput: Boolean(snapshot?.passwordInput),
  655. hasEmailInput: Boolean(snapshot?.emailInput),
  656. hasSubmitButton: Boolean(snapshot?.submitButton),
  657. hasSwitchTrigger: Boolean(snapshot?.switchTrigger),
  658. verificationVisible: Boolean(snapshot?.verificationVisible),
  659. addPhonePage: Boolean(snapshot?.addPhonePage),
  660. oauthConsentPage: Boolean(snapshot?.oauthConsentPage),
  661. consentReady: Boolean(snapshot?.consentReady),
  662. };
  663. }
  664. function getLoginAuthStateLabel(snapshot) {
  665. switch (snapshot?.state) {
  666. case 'verification_page':
  667. return '登录验证码页';
  668. case 'password_page':
  669. return '密码页';
  670. case 'email_page':
  671. return '邮箱输入页';
  672. case 'login_timeout_error_page':
  673. return '登录超时报错页';
  674. case 'oauth_consent_page':
  675. return 'OAuth 授权页';
  676. case 'add_phone_page':
  677. return '手机号页';
  678. default:
  679. return '未知页面';
  680. }
  681. }
  682. async function waitForKnownLoginAuthState(timeout = 15000) {
  683. const start = Date.now();
  684. let snapshot = inspectLoginAuthState();
  685. while (Date.now() - start < timeout) {
  686. throwIfStopped();
  687. snapshot = inspectLoginAuthState();
  688. if (snapshot.state !== 'unknown') {
  689. return snapshot;
  690. }
  691. await sleep(200);
  692. }
  693. return snapshot;
  694. }
  695. async function waitForLoginVerificationPageReady(timeout = 10000) {
  696. const start = Date.now();
  697. let snapshot = inspectLoginAuthState();
  698. while (Date.now() - start < timeout) {
  699. throwIfStopped();
  700. snapshot = inspectLoginAuthState();
  701. if (snapshot.state === 'verification_page') {
  702. return snapshot;
  703. }
  704. if (snapshot.state !== 'unknown') {
  705. break;
  706. }
  707. await sleep(200);
  708. }
  709. throw new Error(
  710. `当前未进入登录验证码页面,请先重新完成步骤 6。当前状态:${getLoginAuthStateLabel(snapshot)}。URL: ${snapshot?.url || location.href}`
  711. );
  712. }
  713. function createStep6SuccessResult(snapshot, options = {}) {
  714. return {
  715. step6Outcome: 'success',
  716. state: snapshot?.state || 'verification_page',
  717. url: snapshot?.url || location.href,
  718. via: options.via || '',
  719. loginVerificationRequestedAt: options.loginVerificationRequestedAt || null,
  720. };
  721. }
  722. function createStep6RecoverableResult(reason, snapshot, options = {}) {
  723. return {
  724. step6Outcome: 'recoverable',
  725. reason,
  726. state: snapshot?.state || 'unknown',
  727. url: snapshot?.url || location.href,
  728. message: options.message || '',
  729. loginVerificationRequestedAt: options.loginVerificationRequestedAt || null,
  730. };
  731. }
  732. function throwForStep6FatalState(snapshot) {
  733. switch (snapshot?.state) {
  734. case 'oauth_consent_page':
  735. throw new Error(`当前页面已进入 OAuth 授权页,未经过登录验证码页,无法完成步骤 6。URL: ${snapshot.url}`);
  736. case 'add_phone_page':
  737. throw new Error(`当前页面已进入手机号页面,未经过登录验证码页,无法完成步骤 6。URL: ${snapshot.url}`);
  738. case 'unknown':
  739. throw new Error(`无法识别当前登录页面状态。URL: ${snapshot?.url || location.href}`);
  740. default:
  741. return;
  742. }
  743. }
  744. async function triggerLoginSubmitAction(button, fallbackField) {
  745. const form = button?.form || fallbackField?.form || button?.closest?.('form') || fallbackField?.closest?.('form') || null;
  746. await humanPause(400, 1100);
  747. if (button && isActionEnabled(button)) {
  748. simulateClick(button);
  749. return;
  750. }
  751. if (form && typeof form.requestSubmit === 'function') {
  752. if (button && button.form === form) {
  753. form.requestSubmit(button);
  754. } else {
  755. form.requestSubmit();
  756. }
  757. return;
  758. }
  759. if (button && typeof button.click === 'function') {
  760. button.click();
  761. return;
  762. }
  763. throw new Error('未找到可用的登录提交按钮。URL: ' + location.href);
  764. }
  765. function isSignupPasswordErrorPage() {
  766. return Boolean(getSignupPasswordTimeoutErrorPageState());
  767. }
  768. function isSignupEmailAlreadyExistsPage() {
  769. return isSignupPasswordPage() && SIGNUP_EMAIL_EXISTS_PATTERN.test(getPageTextSnapshot());
  770. }
  771. function inspectSignupVerificationState() {
  772. if (isStep5Ready()) {
  773. return { state: 'step5' };
  774. }
  775. if (isVerificationPageStillVisible()) {
  776. return { state: 'verification' };
  777. }
  778. if (isSignupPasswordErrorPage()) {
  779. const timeoutPage = getSignupPasswordTimeoutErrorPageState();
  780. return {
  781. state: 'error',
  782. retryButton: timeoutPage?.retryButton || null,
  783. };
  784. }
  785. if (isSignupEmailAlreadyExistsPage()) {
  786. return { state: 'email_exists' };
  787. }
  788. const passwordInput = getSignupPasswordInput();
  789. if (passwordInput) {
  790. return {
  791. state: 'password',
  792. passwordInput,
  793. submitButton: getSignupPasswordSubmitButton({ allowDisabled: true }),
  794. };
  795. }
  796. return { state: 'unknown' };
  797. }
  798. async function waitForSignupVerificationTransition(timeout = 5000) {
  799. const start = Date.now();
  800. while (Date.now() - start < timeout) {
  801. throwIfStopped();
  802. const snapshot = inspectSignupVerificationState();
  803. if (snapshot.state === 'step5' || snapshot.state === 'verification' || snapshot.state === 'error' || snapshot.state === 'email_exists') {
  804. return snapshot;
  805. }
  806. await sleep(200);
  807. }
  808. return inspectSignupVerificationState();
  809. }
  810. async function prepareSignupVerificationFlow(payload = {}, timeout = 30000) {
  811. const { password } = payload;
  812. const start = Date.now();
  813. let recoveryRound = 0;
  814. const maxRecoveryRounds = 3;
  815. while (Date.now() - start < timeout && recoveryRound < maxRecoveryRounds) {
  816. throwIfStopped();
  817. const roundNo = recoveryRound + 1;
  818. log(`步骤 4:等待页面进入验证码阶段(第 ${roundNo}/${maxRecoveryRounds} 轮,先等待 5 秒)...`, 'info');
  819. const snapshot = await waitForSignupVerificationTransition(5000);
  820. if (snapshot.state === 'step5') {
  821. log('步骤 4:页面已进入验证码后的下一阶段,本步骤按已完成处理。', 'ok');
  822. return { ready: true, alreadyVerified: true, retried: recoveryRound };
  823. }
  824. if (snapshot.state === 'verification') {
  825. log(`步骤 4:验证码页面已就绪${recoveryRound ? `(期间自动恢复 ${recoveryRound} 次)` : ''}。`, 'ok');
  826. return { ready: true, retried: recoveryRound };
  827. }
  828. if (snapshot.state === 'email_exists') {
  829. throw new Error('当前邮箱已存在,需要重新开始新一轮。');
  830. }
  831. recoveryRound += 1;
  832. if (snapshot.state === 'error') {
  833. if (snapshot.retryButton && isActionEnabled(snapshot.retryButton)) {
  834. log(`步骤 4:检测到密码页超时报错,正在点击“重试”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  835. await humanPause(350, 900);
  836. simulateClick(snapshot.retryButton);
  837. await sleep(1200);
  838. continue;
  839. }
  840. log(`步骤 4:检测到异常页,但“重试”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  841. continue;
  842. }
  843. if (snapshot.state === 'password') {
  844. if (!password) {
  845. throw new Error('当前回到了密码页,但没有可用密码,无法自动重新提交。');
  846. }
  847. if ((snapshot.passwordInput.value || '') !== password) {
  848. log('步骤 4:页面仍停留在密码页,正在重新填写密码...', 'warn');
  849. await humanPause(450, 1100);
  850. fillInput(snapshot.passwordInput, password);
  851. }
  852. if (snapshot.submitButton && isActionEnabled(snapshot.submitButton)) {
  853. log(`步骤 4:页面仍停留在密码页,正在重新点击“继续”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  854. await humanPause(350, 900);
  855. simulateClick(snapshot.submitButton);
  856. await sleep(1200);
  857. continue;
  858. }
  859. log(`步骤 4:页面仍停留在密码页,但“继续”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  860. continue;
  861. }
  862. log(`步骤 4:页面仍在切换中,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  863. }
  864. throw new Error(`等待注册验证码页面就绪超时或自动恢复失败(已尝试 ${recoveryRound}/${maxRecoveryRounds} 轮)。URL: ${location.href}`);
  865. }
  866. async function waitForVerificationSubmitOutcome(step, timeout) {
  867. const resolvedTimeout = timeout ?? (step === 7 ? 30000 : 12000);
  868. const start = Date.now();
  869. while (Date.now() - start < resolvedTimeout) {
  870. throwIfStopped();
  871. const errorText = getVerificationErrorText();
  872. if (errorText) {
  873. return { invalidCode: true, errorText };
  874. }
  875. if (step === 4 && isStep5Ready()) {
  876. return { success: true };
  877. }
  878. if (step === 7 && isStep8Ready()) {
  879. return { success: true };
  880. }
  881. if (step === 7 && isAddPhonePageReady()) {
  882. return { success: true, addPhonePage: true };
  883. }
  884. await sleep(150);
  885. }
  886. if (isVerificationPageStillVisible()) {
  887. return {
  888. invalidCode: true,
  889. errorText: getVerificationErrorText() || '提交后仍停留在验证码页面,准备重新发送验证码。',
  890. };
  891. }
  892. return { success: true, assumed: true };
  893. }
  894. async function fillVerificationCode(step, payload) {
  895. const { code } = payload;
  896. if (!code) throw new Error('未提供验证码。');
  897. log(`步骤 ${step}:正在填写验证码:${code}`);
  898. if (step === 7) {
  899. await waitForLoginVerificationPageReady();
  900. }
  901. // Find code input — could be a single input or multiple separate inputs
  902. let codeInput = null;
  903. try {
  904. codeInput = await waitForElement(VERIFICATION_CODE_INPUT_SELECTOR, 10000);
  905. } catch {
  906. // Check for multiple single-digit inputs (common pattern)
  907. const singleInputs = document.querySelectorAll('input[maxlength="1"]');
  908. if (singleInputs.length >= 6) {
  909. log(`步骤 ${step}:发现分开的单字符验证码输入框,正在逐个填写...`);
  910. for (let i = 0; i < 6 && i < singleInputs.length; i++) {
  911. fillInput(singleInputs[i], code[i]);
  912. await sleep(100);
  913. }
  914. const outcome = await waitForVerificationSubmitOutcome(step);
  915. if (outcome.invalidCode) {
  916. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  917. } else if (outcome.addPhonePage) {
  918. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  919. } else {
  920. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  921. }
  922. return outcome;
  923. }
  924. throw new Error('未找到验证码输入框。URL: ' + location.href);
  925. }
  926. fillInput(codeInput, code);
  927. log(`步骤 ${step}:验证码已填写`);
  928. // Report complete BEFORE submit (page may navigate away)
  929. // Submit
  930. await sleep(500);
  931. const submitBtn = document.querySelector('button[type="submit"]')
  932. || await waitForElementByText('button', /verify|confirm|submit|continue|确认|验证/i, 5000).catch(() => null);
  933. if (submitBtn) {
  934. await humanPause(450, 1200);
  935. simulateClick(submitBtn);
  936. log(`步骤 ${step}:验证码已提交`);
  937. }
  938. const outcome = await waitForVerificationSubmitOutcome(step);
  939. if (outcome.invalidCode) {
  940. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  941. } else if (outcome.addPhonePage) {
  942. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  943. } else {
  944. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  945. }
  946. return outcome;
  947. }
  948. // ============================================================
  949. // Step 6: Login with registered account (on OAuth auth page)
  950. // ============================================================
  951. async function waitForStep6EmailSubmitTransition(emailSubmittedAt, timeout = 12000) {
  952. const start = Date.now();
  953. let snapshot = inspectLoginAuthState();
  954. while (Date.now() - start < timeout) {
  955. throwIfStopped();
  956. snapshot = inspectLoginAuthState();
  957. if (snapshot.state === 'verification_page') {
  958. return {
  959. action: 'done',
  960. result: createStep6SuccessResult(snapshot, {
  961. via: 'email_submit',
  962. loginVerificationRequestedAt: emailSubmittedAt,
  963. }),
  964. };
  965. }
  966. if (snapshot.state === 'password_page') {
  967. return { action: 'password', snapshot };
  968. }
  969. if (snapshot.state === 'login_timeout_error_page') {
  970. return {
  971. action: 'recoverable',
  972. result: createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  973. message: '提交邮箱后进入登录超时报错页。',
  974. }),
  975. };
  976. }
  977. if (snapshot.state === 'oauth_consent_page') {
  978. throw new Error(`提交邮箱后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  979. }
  980. if (snapshot.state === 'add_phone_page') {
  981. throw new Error(`提交邮箱后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  982. }
  983. await sleep(250);
  984. }
  985. snapshot = inspectLoginAuthState();
  986. if (snapshot.state === 'verification_page') {
  987. return {
  988. action: 'done',
  989. result: createStep6SuccessResult(snapshot, {
  990. via: 'email_submit',
  991. loginVerificationRequestedAt: emailSubmittedAt,
  992. }),
  993. };
  994. }
  995. if (snapshot.state === 'password_page') {
  996. return { action: 'password', snapshot };
  997. }
  998. if (snapshot.state === 'login_timeout_error_page') {
  999. return {
  1000. action: 'recoverable',
  1001. result: createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1002. message: '提交邮箱后进入登录超时报错页。',
  1003. }),
  1004. };
  1005. }
  1006. if (snapshot.state === 'oauth_consent_page') {
  1007. throw new Error(`提交邮箱后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1008. }
  1009. if (snapshot.state === 'add_phone_page') {
  1010. throw new Error(`提交邮箱后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1011. }
  1012. return {
  1013. action: 'recoverable',
  1014. result: createStep6RecoverableResult('email_submit_stalled', snapshot, {
  1015. message: '提交邮箱后长时间未进入密码页或登录验证码页。',
  1016. }),
  1017. };
  1018. }
  1019. async function waitForStep6PasswordSubmitTransition(passwordSubmittedAt, timeout = 10000) {
  1020. const start = Date.now();
  1021. let snapshot = inspectLoginAuthState();
  1022. while (Date.now() - start < timeout) {
  1023. throwIfStopped();
  1024. snapshot = inspectLoginAuthState();
  1025. if (snapshot.state === 'verification_page') {
  1026. return {
  1027. action: 'done',
  1028. result: createStep6SuccessResult(snapshot, {
  1029. via: 'password_submit',
  1030. loginVerificationRequestedAt: passwordSubmittedAt,
  1031. }),
  1032. };
  1033. }
  1034. if (snapshot.state === 'login_timeout_error_page') {
  1035. return {
  1036. action: 'recoverable',
  1037. result: createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1038. message: '提交密码后进入登录超时报错页。',
  1039. }),
  1040. };
  1041. }
  1042. if (snapshot.state === 'oauth_consent_page') {
  1043. throw new Error(`提交密码后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1044. }
  1045. if (snapshot.state === 'add_phone_page') {
  1046. throw new Error(`提交密码后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1047. }
  1048. await sleep(250);
  1049. }
  1050. snapshot = inspectLoginAuthState();
  1051. if (snapshot.state === 'verification_page') {
  1052. return {
  1053. action: 'done',
  1054. result: createStep6SuccessResult(snapshot, {
  1055. via: 'password_submit',
  1056. loginVerificationRequestedAt: passwordSubmittedAt,
  1057. }),
  1058. };
  1059. }
  1060. if (snapshot.state === 'login_timeout_error_page') {
  1061. return {
  1062. action: 'recoverable',
  1063. result: createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1064. message: '提交密码后进入登录超时报错页。',
  1065. }),
  1066. };
  1067. }
  1068. if (snapshot.state === 'oauth_consent_page') {
  1069. throw new Error(`提交密码后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1070. }
  1071. if (snapshot.state === 'add_phone_page') {
  1072. throw new Error(`提交密码后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1073. }
  1074. if (snapshot.state === 'password_page' && snapshot.switchTrigger) {
  1075. return { action: 'switch', snapshot };
  1076. }
  1077. return {
  1078. action: 'recoverable',
  1079. result: createStep6RecoverableResult('password_submit_stalled', snapshot, {
  1080. message: '提交密码后仍未进入登录验证码页。',
  1081. }),
  1082. };
  1083. }
  1084. async function waitForStep6SwitchTransition(loginVerificationRequestedAt, timeout = 10000) {
  1085. const start = Date.now();
  1086. let snapshot = inspectLoginAuthState();
  1087. while (Date.now() - start < timeout) {
  1088. throwIfStopped();
  1089. snapshot = inspectLoginAuthState();
  1090. if (snapshot.state === 'verification_page') {
  1091. return createStep6SuccessResult(snapshot, {
  1092. via: 'switch_to_one_time_code_login',
  1093. loginVerificationRequestedAt,
  1094. });
  1095. }
  1096. if (snapshot.state === 'login_timeout_error_page') {
  1097. return createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1098. message: '切换到一次性验证码登录后进入登录超时报错页。',
  1099. });
  1100. }
  1101. if (snapshot.state === 'oauth_consent_page') {
  1102. throw new Error(`切换到一次性验证码登录后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1103. }
  1104. if (snapshot.state === 'add_phone_page') {
  1105. throw new Error(`切换到一次性验证码登录后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1106. }
  1107. await sleep(250);
  1108. }
  1109. snapshot = inspectLoginAuthState();
  1110. if (snapshot.state === 'verification_page') {
  1111. return createStep6SuccessResult(snapshot, {
  1112. via: 'switch_to_one_time_code_login',
  1113. loginVerificationRequestedAt,
  1114. });
  1115. }
  1116. if (snapshot.state === 'login_timeout_error_page') {
  1117. return createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1118. message: '切换到一次性验证码登录后进入登录超时报错页。',
  1119. });
  1120. }
  1121. if (snapshot.state === 'oauth_consent_page') {
  1122. throw new Error(`切换到一次性验证码登录后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1123. }
  1124. if (snapshot.state === 'add_phone_page') {
  1125. throw new Error(`切换到一次性验证码登录后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1126. }
  1127. return createStep6RecoverableResult('one_time_code_switch_stalled', snapshot, {
  1128. message: '点击一次性验证码登录后仍未进入登录验证码页。',
  1129. });
  1130. }
  1131. async function step6SwitchToOneTimeCodeLogin(snapshot) {
  1132. const switchTrigger = snapshot?.switchTrigger || findOneTimeCodeLoginTrigger();
  1133. if (!switchTrigger || !isActionEnabled(switchTrigger)) {
  1134. return createStep6RecoverableResult('missing_one_time_code_trigger', inspectLoginAuthState(), {
  1135. message: '当前登录页没有可用的一次性验证码登录入口。',
  1136. });
  1137. }
  1138. log('步骤 6:已检测到一次性验证码登录入口,准备切换...');
  1139. const loginVerificationRequestedAt = Date.now();
  1140. await humanPause(350, 900);
  1141. simulateClick(switchTrigger);
  1142. log('步骤 6:已点击一次性验证码登录');
  1143. await sleep(1200);
  1144. return waitForStep6SwitchTransition(loginVerificationRequestedAt);
  1145. }
  1146. async function step6LoginFromPasswordPage(payload, snapshot) {
  1147. const currentSnapshot = snapshot || inspectLoginAuthState();
  1148. if (currentSnapshot.passwordInput) {
  1149. if (!payload.password) {
  1150. throw new Error('登录时缺少密码,步骤 6 无法继续。');
  1151. }
  1152. log('步骤 6:已进入密码页,准备填写密码...');
  1153. await humanPause(550, 1450);
  1154. fillInput(currentSnapshot.passwordInput, payload.password);
  1155. log('步骤 6:已填写密码');
  1156. await sleep(500);
  1157. const passwordSubmittedAt = Date.now();
  1158. await triggerLoginSubmitAction(currentSnapshot.submitButton, currentSnapshot.passwordInput);
  1159. log('步骤 6:已提交密码');
  1160. const transition = await waitForStep6PasswordSubmitTransition(passwordSubmittedAt);
  1161. if (transition.action === 'done') {
  1162. log('步骤 6:已进入登录验证码页面。', 'ok');
  1163. return transition.result;
  1164. }
  1165. if (transition.action === 'recoverable') {
  1166. log(`步骤 6:${transition.result.message || '提交密码后仍未进入登录验证码页面,准备重新执行步骤 6。'}`, 'warn');
  1167. return transition.result;
  1168. }
  1169. if (transition.action === 'switch') {
  1170. return step6SwitchToOneTimeCodeLogin(transition.snapshot);
  1171. }
  1172. return createStep6RecoverableResult('password_submit_unknown', inspectLoginAuthState(), {
  1173. message: '提交密码后未得到可用的下一步状态。',
  1174. });
  1175. }
  1176. if (currentSnapshot.switchTrigger) {
  1177. return step6SwitchToOneTimeCodeLogin(currentSnapshot);
  1178. }
  1179. return createStep6RecoverableResult('password_page_unactionable', currentSnapshot, {
  1180. message: '当前停留在登录页,但没有可提交密码的输入框,也没有一次性验证码登录入口。',
  1181. });
  1182. }
  1183. async function step6LoginFromEmailPage(payload, snapshot) {
  1184. const currentSnapshot = snapshot || inspectLoginAuthState();
  1185. const emailInput = currentSnapshot.emailInput || getLoginEmailInput();
  1186. if (!emailInput) {
  1187. throw new Error('在登录页未找到邮箱输入框。URL: ' + location.href);
  1188. }
  1189. if ((emailInput.value || '').trim() !== payload.email) {
  1190. await humanPause(500, 1400);
  1191. fillInput(emailInput, payload.email);
  1192. log('步骤 6:已填写邮箱');
  1193. } else {
  1194. log('步骤 6:邮箱已在输入框中,准备提交...');
  1195. }
  1196. await sleep(500);
  1197. const emailSubmittedAt = Date.now();
  1198. await triggerLoginSubmitAction(currentSnapshot.submitButton, emailInput);
  1199. log('步骤 6:已提交邮箱');
  1200. const transition = await waitForStep6EmailSubmitTransition(emailSubmittedAt);
  1201. if (transition.action === 'done') {
  1202. log('步骤 6:已进入登录验证码页面。', 'ok');
  1203. return transition.result;
  1204. }
  1205. if (transition.action === 'recoverable') {
  1206. log(`步骤 6:${transition.result.message || '提交邮箱后仍未进入目标页面,准备重新执行步骤 6。'}`, 'warn');
  1207. return transition.result;
  1208. }
  1209. if (transition.action === 'password') {
  1210. return step6LoginFromPasswordPage(payload, transition.snapshot);
  1211. }
  1212. return createStep6RecoverableResult('email_submit_unknown', inspectLoginAuthState(), {
  1213. message: '提交邮箱后未得到可用的下一步状态。',
  1214. });
  1215. }
  1216. async function step6_login(payload) {
  1217. const { email } = payload;
  1218. if (!email) throw new Error('登录时缺少邮箱地址。');
  1219. log(`步骤 6:正在使用 ${email} 登录...`);
  1220. const snapshot = await waitForKnownLoginAuthState(15000);
  1221. if (snapshot.state === 'verification_page') {
  1222. log('步骤 6:登录验证码页面已就绪。', 'ok');
  1223. return createStep6SuccessResult(snapshot, { via: 'already_on_verification_page' });
  1224. }
  1225. if (snapshot.state === 'login_timeout_error_page') {
  1226. log('步骤 6:检测到登录超时报错,准备重新执行步骤 6。', 'warn');
  1227. return createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1228. message: '当前页面处于登录超时报错页。',
  1229. });
  1230. }
  1231. if (snapshot.state === 'email_page') {
  1232. return step6LoginFromEmailPage(payload, snapshot);
  1233. }
  1234. if (snapshot.state === 'password_page') {
  1235. return step6LoginFromPasswordPage(payload, snapshot);
  1236. }
  1237. throwForStep6FatalState(snapshot);
  1238. throw new Error(`无法识别当前登录页面状态。URL: ${snapshot?.url || location.href}`);
  1239. }
  1240. // ============================================================
  1241. // Step 8: Find "继续" on OAuth consent page for debugger click
  1242. // ============================================================
  1243. // After login + verification, page shows:
  1244. // "使用 ChatGPT 登录到 Codex" with a "继续" submit button.
  1245. // Background performs the actual click through the debugger Input API.
  1246. async function step8_findAndClick() {
  1247. log('步骤 8:正在查找 OAuth 同意页的“继续”按钮...');
  1248. const continueBtn = await prepareStep8ContinueButton();
  1249. const rect = getSerializableRect(continueBtn);
  1250. log('步骤 8:已找到“继续”按钮并准备好调试器点击坐标。');
  1251. return {
  1252. rect,
  1253. buttonText: (continueBtn.textContent || '').trim(),
  1254. url: location.href,
  1255. };
  1256. }
  1257. function getStep8State() {
  1258. const continueBtn = getPrimaryContinueButton();
  1259. const state = {
  1260. url: location.href,
  1261. consentPage: isOAuthConsentPage(),
  1262. consentReady: isStep8Ready(),
  1263. verificationPage: isVerificationPageStillVisible(),
  1264. addPhonePage: isAddPhonePageReady(),
  1265. buttonFound: Boolean(continueBtn),
  1266. buttonEnabled: isButtonEnabled(continueBtn),
  1267. buttonText: continueBtn ? getActionText(continueBtn) : '',
  1268. };
  1269. if (continueBtn) {
  1270. try {
  1271. state.rect = getSerializableRect(continueBtn);
  1272. } catch {
  1273. state.rect = null;
  1274. }
  1275. }
  1276. return state;
  1277. }
  1278. async function step8_triggerContinue(payload = {}) {
  1279. const strategy = payload?.strategy || 'requestSubmit';
  1280. const continueBtn = await prepareStep8ContinueButton({
  1281. findTimeoutMs: payload?.findTimeoutMs,
  1282. enabledTimeoutMs: payload?.enabledTimeoutMs,
  1283. });
  1284. const form = continueBtn.form || continueBtn.closest('form');
  1285. switch (strategy) {
  1286. case 'requestSubmit':
  1287. if (!form || typeof form.requestSubmit !== 'function') {
  1288. throw new Error('“继续”按钮当前不在可提交的 form 中,无法使用 requestSubmit。URL: ' + location.href);
  1289. }
  1290. form.requestSubmit(continueBtn);
  1291. break;
  1292. case 'nativeClick':
  1293. continueBtn.click();
  1294. break;
  1295. case 'dispatchClick':
  1296. simulateClick(continueBtn);
  1297. break;
  1298. default:
  1299. throw new Error(`未知的 Step 8 触发策略:${strategy}`);
  1300. }
  1301. log(`Step 8: continue button triggered via ${strategy}.`);
  1302. return {
  1303. strategy,
  1304. ...getStep8State(),
  1305. };
  1306. }
  1307. async function prepareStep8ContinueButton(options = {}) {
  1308. const {
  1309. findTimeoutMs = 10000,
  1310. enabledTimeoutMs = 8000,
  1311. } = options;
  1312. const continueBtn = await findContinueButton(findTimeoutMs);
  1313. await waitForButtonEnabled(continueBtn, enabledTimeoutMs);
  1314. await humanPause(250, 700);
  1315. continueBtn.scrollIntoView({ behavior: 'auto', block: 'center' });
  1316. continueBtn.focus();
  1317. await waitForStableButtonRect(continueBtn);
  1318. return continueBtn;
  1319. }
  1320. async function findContinueButton(timeout = 10000) {
  1321. const start = Date.now();
  1322. while (Date.now() - start < timeout) {
  1323. throwIfStopped();
  1324. if (isAddPhonePageReady()) {
  1325. throw new Error('当前页面已进入手机号页面,不是 OAuth 授权同意页。URL: ' + location.href);
  1326. }
  1327. const button = getPrimaryContinueButton();
  1328. if (button && isStep8Ready()) {
  1329. return button;
  1330. }
  1331. await sleep(150);
  1332. }
  1333. throw new Error('在 OAuth 同意页未找到“继续”按钮,或页面尚未进入授权同意状态。URL: ' + location.href);
  1334. }
  1335. async function waitForButtonEnabled(button, timeout = 8000) {
  1336. const start = Date.now();
  1337. while (Date.now() - start < timeout) {
  1338. throwIfStopped();
  1339. if (isButtonEnabled(button)) return;
  1340. await sleep(150);
  1341. }
  1342. throw new Error('“继续”按钮长时间不可点击。URL: ' + location.href);
  1343. }
  1344. function isButtonEnabled(button) {
  1345. return Boolean(button)
  1346. && !button.disabled
  1347. && button.getAttribute('aria-disabled') !== 'true';
  1348. }
  1349. async function waitForStableButtonRect(button, timeout = 1500) {
  1350. let previous = null;
  1351. let stableSamples = 0;
  1352. const start = Date.now();
  1353. while (Date.now() - start < timeout) {
  1354. throwIfStopped();
  1355. const rect = button?.getBoundingClientRect?.();
  1356. if (rect && rect.width > 0 && rect.height > 0) {
  1357. const snapshot = {
  1358. left: rect.left,
  1359. top: rect.top,
  1360. width: rect.width,
  1361. height: rect.height,
  1362. };
  1363. if (
  1364. previous
  1365. && Math.abs(snapshot.left - previous.left) < 1
  1366. && Math.abs(snapshot.top - previous.top) < 1
  1367. && Math.abs(snapshot.width - previous.width) < 1
  1368. && Math.abs(snapshot.height - previous.height) < 1
  1369. ) {
  1370. stableSamples += 1;
  1371. if (stableSamples >= 2) {
  1372. return;
  1373. }
  1374. } else {
  1375. stableSamples = 0;
  1376. }
  1377. previous = snapshot;
  1378. }
  1379. await sleep(80);
  1380. }
  1381. }
  1382. function getSerializableRect(el) {
  1383. const rect = el.getBoundingClientRect();
  1384. if (!rect.width || !rect.height) {
  1385. throw new Error('滚动后“继续”按钮没有可点击尺寸。URL: ' + location.href);
  1386. }
  1387. return {
  1388. left: rect.left,
  1389. top: rect.top,
  1390. width: rect.width,
  1391. height: rect.height,
  1392. centerX: rect.left + (rect.width / 2),
  1393. centerY: rect.top + (rect.height / 2),
  1394. };
  1395. }
  1396. // ============================================================
  1397. // Step 5: Fill Name & Birthday / Age
  1398. // ============================================================
  1399. async function step5_fillNameBirthday(payload) {
  1400. const { firstName, lastName, age, year, month, day } = payload;
  1401. if (!firstName || !lastName) throw new Error('未提供姓名数据。');
  1402. const resolvedAge = age ?? (year ? new Date().getFullYear() - Number(year) : null);
  1403. const hasBirthdayData = [year, month, day].every(value => value != null && !Number.isNaN(Number(value)));
  1404. if (!hasBirthdayData && (resolvedAge == null || Number.isNaN(Number(resolvedAge)))) {
  1405. throw new Error('未提供生日或年龄数据。');
  1406. }
  1407. const fullName = `${firstName} ${lastName}`;
  1408. log(`步骤 5:正在填写姓名:${fullName}`);
  1409. // Actual DOM structure:
  1410. // - Full name: <input name="name" placeholder="全名" type="text">
  1411. // - Birthday: React Aria DateField or hidden input[name="birthday"]
  1412. // - Age: <input name="age" type="text|number">
  1413. // --- Full Name (single field, not first+last) ---
  1414. let nameInput = null;
  1415. try {
  1416. nameInput = await waitForElement(
  1417. 'input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]',
  1418. 10000
  1419. );
  1420. } catch {
  1421. throw new Error('未找到姓名输入框。URL: ' + location.href);
  1422. }
  1423. await humanPause(500, 1300);
  1424. fillInput(nameInput, fullName);
  1425. log(`步骤 5:姓名已填写:${fullName}`);
  1426. let birthdayMode = false;
  1427. let ageInput = null;
  1428. let yearSpinner = null;
  1429. let monthSpinner = null;
  1430. let daySpinner = null;
  1431. let hiddenBirthday = null;
  1432. let yearReactSelect = null;
  1433. let monthReactSelect = null;
  1434. let dayReactSelect = null;
  1435. let visibleAgeInput = false;
  1436. let visibleBirthdaySpinners = false;
  1437. let visibleBirthdaySelects = false;
  1438. for (let i = 0; i < 100; i++) {
  1439. yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  1440. monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  1441. daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  1442. hiddenBirthday = document.querySelector('input[name="birthday"]');
  1443. ageInput = document.querySelector('input[name="age"]');
  1444. yearReactSelect = findBirthdayReactAriaSelect('年');
  1445. monthReactSelect = findBirthdayReactAriaSelect('月');
  1446. dayReactSelect = findBirthdayReactAriaSelect('天');
  1447. visibleAgeInput = Boolean(ageInput && isVisibleElement(ageInput));
  1448. visibleBirthdaySpinners = Boolean(
  1449. yearSpinner
  1450. && monthSpinner
  1451. && daySpinner
  1452. && isVisibleElement(yearSpinner)
  1453. && isVisibleElement(monthSpinner)
  1454. && isVisibleElement(daySpinner)
  1455. );
  1456. visibleBirthdaySelects = Boolean(
  1457. yearReactSelect?.button
  1458. && monthReactSelect?.button
  1459. && dayReactSelect?.button
  1460. && isVisibleElement(yearReactSelect.button)
  1461. && isVisibleElement(monthReactSelect.button)
  1462. && isVisibleElement(dayReactSelect.button)
  1463. );
  1464. if (visibleAgeInput) break;
  1465. if (visibleBirthdaySpinners || visibleBirthdaySelects) {
  1466. birthdayMode = true;
  1467. break;
  1468. }
  1469. await sleep(100);
  1470. }
  1471. if (birthdayMode) {
  1472. if (!hasBirthdayData) {
  1473. throw new Error('检测到生日字段,但未提供生日数据。');
  1474. }
  1475. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  1476. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  1477. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  1478. const yearReactSelect = findBirthdayReactAriaSelect('年');
  1479. const monthReactSelect = findBirthdayReactAriaSelect('月');
  1480. const dayReactSelect = findBirthdayReactAriaSelect('天');
  1481. if (yearReactSelect?.nativeSelect && monthReactSelect?.nativeSelect && dayReactSelect?.nativeSelect) {
  1482. const desiredDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1483. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1484. log('步骤 5:检测到 React Aria 下拉生日字段,正在填写生日...');
  1485. await humanPause(450, 1100);
  1486. await setReactAriaBirthdaySelect(yearReactSelect, year);
  1487. await humanPause(250, 650);
  1488. await setReactAriaBirthdaySelect(monthReactSelect, month);
  1489. await humanPause(250, 650);
  1490. await setReactAriaBirthdaySelect(dayReactSelect, day);
  1491. if (hiddenBirthday) {
  1492. const start = Date.now();
  1493. while (Date.now() - start < 2000) {
  1494. if ((hiddenBirthday.value || '') === desiredDate) break;
  1495. await sleep(100);
  1496. }
  1497. if ((hiddenBirthday.value || '') !== desiredDate) {
  1498. throw new Error(`生日值未成功写入页面。期望 ${desiredDate},实际 ${(hiddenBirthday.value || '空')}。`);
  1499. }
  1500. }
  1501. log(`步骤 5:React Aria 生日已填写:${desiredDate}`);
  1502. }
  1503. if (yearSpinner && monthSpinner && daySpinner) {
  1504. log('步骤 5:检测到生日字段,正在填写生日...');
  1505. async function setSpinButton(el, value) {
  1506. el.focus();
  1507. await sleep(100);
  1508. document.execCommand('selectAll', false, null);
  1509. await sleep(50);
  1510. const valueStr = String(value);
  1511. for (const char of valueStr) {
  1512. el.dispatchEvent(new KeyboardEvent('keydown', { key: char, code: `Digit${char}`, bubbles: true }));
  1513. el.dispatchEvent(new KeyboardEvent('keypress', { key: char, code: `Digit${char}`, bubbles: true }));
  1514. el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: char, bubbles: true }));
  1515. el.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: char, bubbles: true }));
  1516. await sleep(50);
  1517. }
  1518. el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab', code: 'Tab', bubbles: true }));
  1519. el.blur();
  1520. await sleep(100);
  1521. }
  1522. await humanPause(450, 1100);
  1523. await setSpinButton(yearSpinner, year);
  1524. await humanPause(250, 650);
  1525. await setSpinButton(monthSpinner, String(month).padStart(2, '0'));
  1526. await humanPause(250, 650);
  1527. await setSpinButton(daySpinner, String(day).padStart(2, '0'));
  1528. log(`步骤 5:生日已填写:${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
  1529. }
  1530. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1531. if (hiddenBirthday) {
  1532. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1533. hiddenBirthday.value = dateStr;
  1534. hiddenBirthday.dispatchEvent(new Event('input', { bubbles: true }));
  1535. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  1536. log(`步骤 5:已设置隐藏生日输入框:${dateStr}`);
  1537. }
  1538. } else if (ageInput) {
  1539. if (resolvedAge == null || Number.isNaN(Number(resolvedAge))) {
  1540. throw new Error('检测到年龄字段,但未提供年龄数据。');
  1541. }
  1542. await humanPause(500, 1300);
  1543. fillInput(ageInput, String(resolvedAge));
  1544. log(`步骤 5:年龄已填写:${resolvedAge}`);
  1545. } else {
  1546. throw new Error('未找到生日或年龄输入项。URL: ' + location.href);
  1547. }
  1548. // Click "完成帐户创建" button
  1549. await sleep(500);
  1550. const completeBtn = document.querySelector('button[type="submit"]')
  1551. || await waitForElementByText('button', /完成|create|continue|finish|done|agree/i, 5000).catch(() => null);
  1552. if (!completeBtn) {
  1553. throw new Error('未找到“完成帐户创建”按钮。URL: ' + location.href);
  1554. }
  1555. await humanPause(500, 1300);
  1556. simulateClick(completeBtn);
  1557. log('步骤 5:已点击“完成帐户创建”,正在等待页面结果...');
  1558. const outcome = await waitForStep5SubmitOutcome();
  1559. if (outcome.invalidProfile) {
  1560. throw new Error(`步骤 5:${outcome.errorText}`);
  1561. }
  1562. log(`步骤 5:资料已通过。`, 'ok');
  1563. reportComplete(5, { addPhonePage: Boolean(outcome.addPhonePage) });
  1564. }