signup-page.js 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845
  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/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 || verificationVisible) {
  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. return baseState;
  638. }
  639. function serializeLoginAuthState(snapshot) {
  640. return {
  641. state: snapshot?.state || 'unknown',
  642. url: snapshot?.url || location.href,
  643. path: snapshot?.path || location.pathname || '',
  644. retryEnabled: Boolean(snapshot?.retryEnabled),
  645. titleMatched: Boolean(snapshot?.titleMatched),
  646. detailMatched: Boolean(snapshot?.detailMatched),
  647. hasVerificationTarget: Boolean(snapshot?.verificationTarget),
  648. hasPasswordInput: Boolean(snapshot?.passwordInput),
  649. hasEmailInput: Boolean(snapshot?.emailInput),
  650. hasSubmitButton: Boolean(snapshot?.submitButton),
  651. hasSwitchTrigger: Boolean(snapshot?.switchTrigger),
  652. verificationVisible: Boolean(snapshot?.verificationVisible),
  653. addPhonePage: Boolean(snapshot?.addPhonePage),
  654. oauthConsentPage: Boolean(snapshot?.oauthConsentPage),
  655. consentReady: Boolean(snapshot?.consentReady),
  656. };
  657. }
  658. function getLoginAuthStateLabel(snapshot) {
  659. switch (snapshot?.state) {
  660. case 'verification_page':
  661. return '登录验证码页';
  662. case 'password_page':
  663. return '密码页';
  664. case 'email_page':
  665. return '邮箱输入页';
  666. case 'login_timeout_error_page':
  667. return '登录超时报错页';
  668. case 'oauth_consent_page':
  669. return 'OAuth 授权页';
  670. case 'add_phone_page':
  671. return '手机号页';
  672. default:
  673. return '未知页面';
  674. }
  675. }
  676. async function waitForKnownLoginAuthState(timeout = 15000) {
  677. const start = Date.now();
  678. let snapshot = inspectLoginAuthState();
  679. while (Date.now() - start < timeout) {
  680. throwIfStopped();
  681. snapshot = inspectLoginAuthState();
  682. if (snapshot.state !== 'unknown') {
  683. return snapshot;
  684. }
  685. await sleep(200);
  686. }
  687. return snapshot;
  688. }
  689. async function waitForLoginVerificationPageReady(timeout = 10000) {
  690. const start = Date.now();
  691. let snapshot = inspectLoginAuthState();
  692. while (Date.now() - start < timeout) {
  693. throwIfStopped();
  694. snapshot = inspectLoginAuthState();
  695. if (snapshot.state === 'verification_page') {
  696. return snapshot;
  697. }
  698. if (snapshot.state !== 'unknown') {
  699. break;
  700. }
  701. await sleep(200);
  702. }
  703. throw new Error(
  704. `当前未进入登录验证码页面,请先重新完成步骤 6。当前状态:${getLoginAuthStateLabel(snapshot)}。URL: ${snapshot?.url || location.href}`
  705. );
  706. }
  707. function createStep6SuccessResult(snapshot, options = {}) {
  708. return {
  709. step6Outcome: 'success',
  710. state: snapshot?.state || 'verification_page',
  711. url: snapshot?.url || location.href,
  712. via: options.via || '',
  713. loginVerificationRequestedAt: options.loginVerificationRequestedAt || null,
  714. };
  715. }
  716. function createStep6RecoverableResult(reason, snapshot, options = {}) {
  717. return {
  718. step6Outcome: 'recoverable',
  719. reason,
  720. state: snapshot?.state || 'unknown',
  721. url: snapshot?.url || location.href,
  722. message: options.message || '',
  723. loginVerificationRequestedAt: options.loginVerificationRequestedAt || null,
  724. };
  725. }
  726. function throwForStep6FatalState(snapshot) {
  727. switch (snapshot?.state) {
  728. case 'oauth_consent_page':
  729. throw new Error(`当前页面已进入 OAuth 授权页,未经过登录验证码页,无法完成步骤 6。URL: ${snapshot.url}`);
  730. case 'add_phone_page':
  731. throw new Error(`当前页面已进入手机号页面,未经过登录验证码页,无法完成步骤 6。URL: ${snapshot.url}`);
  732. case 'unknown':
  733. throw new Error(`无法识别当前登录页面状态。URL: ${snapshot?.url || location.href}`);
  734. default:
  735. return;
  736. }
  737. }
  738. async function triggerLoginSubmitAction(button, fallbackField) {
  739. const form = button?.form || fallbackField?.form || button?.closest?.('form') || fallbackField?.closest?.('form') || null;
  740. await humanPause(400, 1100);
  741. if (button && isActionEnabled(button)) {
  742. simulateClick(button);
  743. return;
  744. }
  745. if (form && typeof form.requestSubmit === 'function') {
  746. if (button && button.form === form) {
  747. form.requestSubmit(button);
  748. } else {
  749. form.requestSubmit();
  750. }
  751. return;
  752. }
  753. if (button && typeof button.click === 'function') {
  754. button.click();
  755. return;
  756. }
  757. throw new Error('未找到可用的登录提交按钮。URL: ' + location.href);
  758. }
  759. function isSignupPasswordErrorPage() {
  760. return Boolean(getSignupPasswordTimeoutErrorPageState());
  761. }
  762. function isSignupEmailAlreadyExistsPage() {
  763. return isSignupPasswordPage() && SIGNUP_EMAIL_EXISTS_PATTERN.test(getPageTextSnapshot());
  764. }
  765. function inspectSignupVerificationState() {
  766. if (isStep5Ready()) {
  767. return { state: 'step5' };
  768. }
  769. if (isVerificationPageStillVisible()) {
  770. return { state: 'verification' };
  771. }
  772. if (isSignupPasswordErrorPage()) {
  773. const timeoutPage = getSignupPasswordTimeoutErrorPageState();
  774. return {
  775. state: 'error',
  776. retryButton: timeoutPage?.retryButton || null,
  777. };
  778. }
  779. if (isSignupEmailAlreadyExistsPage()) {
  780. return { state: 'email_exists' };
  781. }
  782. const passwordInput = getSignupPasswordInput();
  783. if (passwordInput) {
  784. return {
  785. state: 'password',
  786. passwordInput,
  787. submitButton: getSignupPasswordSubmitButton({ allowDisabled: true }),
  788. };
  789. }
  790. return { state: 'unknown' };
  791. }
  792. async function waitForSignupVerificationTransition(timeout = 5000) {
  793. const start = Date.now();
  794. while (Date.now() - start < timeout) {
  795. throwIfStopped();
  796. const snapshot = inspectSignupVerificationState();
  797. if (snapshot.state === 'step5' || snapshot.state === 'verification' || snapshot.state === 'error' || snapshot.state === 'email_exists') {
  798. return snapshot;
  799. }
  800. await sleep(200);
  801. }
  802. return inspectSignupVerificationState();
  803. }
  804. async function prepareSignupVerificationFlow(payload = {}, timeout = 30000) {
  805. const { password } = payload;
  806. const start = Date.now();
  807. let recoveryRound = 0;
  808. const maxRecoveryRounds = 3;
  809. while (Date.now() - start < timeout && recoveryRound < maxRecoveryRounds) {
  810. throwIfStopped();
  811. const roundNo = recoveryRound + 1;
  812. log(`步骤 4:等待页面进入验证码阶段(第 ${roundNo}/${maxRecoveryRounds} 轮,先等待 5 秒)...`, 'info');
  813. const snapshot = await waitForSignupVerificationTransition(5000);
  814. if (snapshot.state === 'step5') {
  815. log('步骤 4:页面已进入验证码后的下一阶段,本步骤按已完成处理。', 'ok');
  816. return { ready: true, alreadyVerified: true, retried: recoveryRound };
  817. }
  818. if (snapshot.state === 'verification') {
  819. log(`步骤 4:验证码页面已就绪${recoveryRound ? `(期间自动恢复 ${recoveryRound} 次)` : ''}。`, 'ok');
  820. return { ready: true, retried: recoveryRound };
  821. }
  822. if (snapshot.state === 'email_exists') {
  823. throw new Error('当前邮箱已存在,需要重新开始新一轮。');
  824. }
  825. recoveryRound += 1;
  826. if (snapshot.state === 'error') {
  827. if (snapshot.retryButton && isActionEnabled(snapshot.retryButton)) {
  828. log(`步骤 4:检测到密码页超时报错,正在点击“重试”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  829. await humanPause(350, 900);
  830. simulateClick(snapshot.retryButton);
  831. await sleep(1200);
  832. continue;
  833. }
  834. log(`步骤 4:检测到异常页,但“重试”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  835. continue;
  836. }
  837. if (snapshot.state === 'password') {
  838. if (!password) {
  839. throw new Error('当前回到了密码页,但没有可用密码,无法自动重新提交。');
  840. }
  841. if ((snapshot.passwordInput.value || '') !== password) {
  842. log('步骤 4:页面仍停留在密码页,正在重新填写密码...', 'warn');
  843. await humanPause(450, 1100);
  844. fillInput(snapshot.passwordInput, password);
  845. }
  846. if (snapshot.submitButton && isActionEnabled(snapshot.submitButton)) {
  847. log(`步骤 4:页面仍停留在密码页,正在重新点击“继续”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  848. await humanPause(350, 900);
  849. simulateClick(snapshot.submitButton);
  850. await sleep(1200);
  851. continue;
  852. }
  853. log(`步骤 4:页面仍停留在密码页,但“继续”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  854. continue;
  855. }
  856. log(`步骤 4:页面仍在切换中,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  857. }
  858. throw new Error(`等待注册验证码页面就绪超时或自动恢复失败(已尝试 ${recoveryRound}/${maxRecoveryRounds} 轮)。URL: ${location.href}`);
  859. }
  860. async function waitForVerificationSubmitOutcome(step, timeout) {
  861. const resolvedTimeout = timeout ?? (step === 7 ? 30000 : 12000);
  862. const start = Date.now();
  863. while (Date.now() - start < resolvedTimeout) {
  864. throwIfStopped();
  865. const errorText = getVerificationErrorText();
  866. if (errorText) {
  867. return { invalidCode: true, errorText };
  868. }
  869. if (step === 4 && isStep5Ready()) {
  870. return { success: true };
  871. }
  872. if (step === 7 && isStep8Ready()) {
  873. return { success: true };
  874. }
  875. if (step === 7 && isAddPhonePageReady()) {
  876. return { success: true, addPhonePage: true };
  877. }
  878. await sleep(150);
  879. }
  880. if (isVerificationPageStillVisible()) {
  881. return {
  882. invalidCode: true,
  883. errorText: getVerificationErrorText() || '提交后仍停留在验证码页面,准备重新发送验证码。',
  884. };
  885. }
  886. return { success: true, assumed: true };
  887. }
  888. async function fillVerificationCode(step, payload) {
  889. const { code } = payload;
  890. if (!code) throw new Error('未提供验证码。');
  891. log(`步骤 ${step}:正在填写验证码:${code}`);
  892. if (step === 7) {
  893. await waitForLoginVerificationPageReady();
  894. }
  895. // Find code input — could be a single input or multiple separate inputs
  896. let codeInput = null;
  897. try {
  898. codeInput = await waitForElement(VERIFICATION_CODE_INPUT_SELECTOR, 10000);
  899. } catch {
  900. // Check for multiple single-digit inputs (common pattern)
  901. const singleInputs = document.querySelectorAll('input[maxlength="1"]');
  902. if (singleInputs.length >= 6) {
  903. log(`步骤 ${step}:发现分开的单字符验证码输入框,正在逐个填写...`);
  904. for (let i = 0; i < 6 && i < singleInputs.length; i++) {
  905. fillInput(singleInputs[i], code[i]);
  906. await sleep(100);
  907. }
  908. const outcome = await waitForVerificationSubmitOutcome(step);
  909. if (outcome.invalidCode) {
  910. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  911. } else if (outcome.addPhonePage) {
  912. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  913. } else {
  914. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  915. }
  916. return outcome;
  917. }
  918. throw new Error('未找到验证码输入框。URL: ' + location.href);
  919. }
  920. fillInput(codeInput, code);
  921. log(`步骤 ${step}:验证码已填写`);
  922. // Report complete BEFORE submit (page may navigate away)
  923. // Submit
  924. await sleep(500);
  925. const submitBtn = document.querySelector('button[type="submit"]')
  926. || await waitForElementByText('button', /verify|confirm|submit|continue|确认|验证/i, 5000).catch(() => null);
  927. if (submitBtn) {
  928. await humanPause(450, 1200);
  929. simulateClick(submitBtn);
  930. log(`步骤 ${step}:验证码已提交`);
  931. }
  932. const outcome = await waitForVerificationSubmitOutcome(step);
  933. if (outcome.invalidCode) {
  934. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  935. } else if (outcome.addPhonePage) {
  936. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  937. } else {
  938. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  939. }
  940. return outcome;
  941. }
  942. // ============================================================
  943. // Step 6: Login with registered account (on OAuth auth page)
  944. // ============================================================
  945. async function waitForStep6EmailSubmitTransition(emailSubmittedAt, timeout = 12000) {
  946. const start = Date.now();
  947. let snapshot = inspectLoginAuthState();
  948. while (Date.now() - start < timeout) {
  949. throwIfStopped();
  950. snapshot = inspectLoginAuthState();
  951. if (snapshot.state === 'verification_page') {
  952. return {
  953. action: 'done',
  954. result: createStep6SuccessResult(snapshot, {
  955. via: 'email_submit',
  956. loginVerificationRequestedAt: emailSubmittedAt,
  957. }),
  958. };
  959. }
  960. if (snapshot.state === 'password_page') {
  961. return { action: 'password', snapshot };
  962. }
  963. if (snapshot.state === 'login_timeout_error_page') {
  964. return {
  965. action: 'recoverable',
  966. result: createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  967. message: '提交邮箱后进入登录超时报错页。',
  968. }),
  969. };
  970. }
  971. if (snapshot.state === 'oauth_consent_page') {
  972. throw new Error(`提交邮箱后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  973. }
  974. if (snapshot.state === 'add_phone_page') {
  975. throw new Error(`提交邮箱后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  976. }
  977. await sleep(250);
  978. }
  979. snapshot = inspectLoginAuthState();
  980. if (snapshot.state === 'verification_page') {
  981. return {
  982. action: 'done',
  983. result: createStep6SuccessResult(snapshot, {
  984. via: 'email_submit',
  985. loginVerificationRequestedAt: emailSubmittedAt,
  986. }),
  987. };
  988. }
  989. if (snapshot.state === 'password_page') {
  990. return { action: 'password', snapshot };
  991. }
  992. if (snapshot.state === 'login_timeout_error_page') {
  993. return {
  994. action: 'recoverable',
  995. result: createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  996. message: '提交邮箱后进入登录超时报错页。',
  997. }),
  998. };
  999. }
  1000. if (snapshot.state === 'oauth_consent_page') {
  1001. throw new Error(`提交邮箱后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1002. }
  1003. if (snapshot.state === 'add_phone_page') {
  1004. throw new Error(`提交邮箱后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1005. }
  1006. return {
  1007. action: 'recoverable',
  1008. result: createStep6RecoverableResult('email_submit_stalled', snapshot, {
  1009. message: '提交邮箱后长时间未进入密码页或登录验证码页。',
  1010. }),
  1011. };
  1012. }
  1013. async function waitForStep6PasswordSubmitTransition(passwordSubmittedAt, timeout = 10000) {
  1014. const start = Date.now();
  1015. let snapshot = inspectLoginAuthState();
  1016. while (Date.now() - start < timeout) {
  1017. throwIfStopped();
  1018. snapshot = inspectLoginAuthState();
  1019. if (snapshot.state === 'verification_page') {
  1020. return {
  1021. action: 'done',
  1022. result: createStep6SuccessResult(snapshot, {
  1023. via: 'password_submit',
  1024. loginVerificationRequestedAt: passwordSubmittedAt,
  1025. }),
  1026. };
  1027. }
  1028. if (snapshot.state === 'login_timeout_error_page') {
  1029. return {
  1030. action: 'recoverable',
  1031. result: createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1032. message: '提交密码后进入登录超时报错页。',
  1033. }),
  1034. };
  1035. }
  1036. if (snapshot.state === 'oauth_consent_page') {
  1037. throw new Error(`提交密码后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1038. }
  1039. if (snapshot.state === 'add_phone_page') {
  1040. throw new Error(`提交密码后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1041. }
  1042. await sleep(250);
  1043. }
  1044. snapshot = inspectLoginAuthState();
  1045. if (snapshot.state === 'verification_page') {
  1046. return {
  1047. action: 'done',
  1048. result: createStep6SuccessResult(snapshot, {
  1049. via: 'password_submit',
  1050. loginVerificationRequestedAt: passwordSubmittedAt,
  1051. }),
  1052. };
  1053. }
  1054. if (snapshot.state === 'login_timeout_error_page') {
  1055. return {
  1056. action: 'recoverable',
  1057. result: createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1058. message: '提交密码后进入登录超时报错页。',
  1059. }),
  1060. };
  1061. }
  1062. if (snapshot.state === 'oauth_consent_page') {
  1063. throw new Error(`提交密码后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1064. }
  1065. if (snapshot.state === 'add_phone_page') {
  1066. throw new Error(`提交密码后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1067. }
  1068. if (snapshot.state === 'password_page' && snapshot.switchTrigger) {
  1069. return { action: 'switch', snapshot };
  1070. }
  1071. return {
  1072. action: 'recoverable',
  1073. result: createStep6RecoverableResult('password_submit_stalled', snapshot, {
  1074. message: '提交密码后仍未进入登录验证码页。',
  1075. }),
  1076. };
  1077. }
  1078. async function waitForStep6SwitchTransition(loginVerificationRequestedAt, timeout = 10000) {
  1079. const start = Date.now();
  1080. let snapshot = inspectLoginAuthState();
  1081. while (Date.now() - start < timeout) {
  1082. throwIfStopped();
  1083. snapshot = inspectLoginAuthState();
  1084. if (snapshot.state === 'verification_page') {
  1085. return createStep6SuccessResult(snapshot, {
  1086. via: 'switch_to_one_time_code_login',
  1087. loginVerificationRequestedAt,
  1088. });
  1089. }
  1090. if (snapshot.state === 'login_timeout_error_page') {
  1091. return createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1092. message: '切换到一次性验证码登录后进入登录超时报错页。',
  1093. });
  1094. }
  1095. if (snapshot.state === 'oauth_consent_page') {
  1096. throw new Error(`切换到一次性验证码登录后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1097. }
  1098. if (snapshot.state === 'add_phone_page') {
  1099. throw new Error(`切换到一次性验证码登录后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1100. }
  1101. await sleep(250);
  1102. }
  1103. snapshot = inspectLoginAuthState();
  1104. if (snapshot.state === 'verification_page') {
  1105. return createStep6SuccessResult(snapshot, {
  1106. via: 'switch_to_one_time_code_login',
  1107. loginVerificationRequestedAt,
  1108. });
  1109. }
  1110. if (snapshot.state === 'login_timeout_error_page') {
  1111. return createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1112. message: '切换到一次性验证码登录后进入登录超时报错页。',
  1113. });
  1114. }
  1115. if (snapshot.state === 'oauth_consent_page') {
  1116. throw new Error(`切换到一次性验证码登录后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1117. }
  1118. if (snapshot.state === 'add_phone_page') {
  1119. throw new Error(`切换到一次性验证码登录后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1120. }
  1121. return createStep6RecoverableResult('one_time_code_switch_stalled', snapshot, {
  1122. message: '点击一次性验证码登录后仍未进入登录验证码页。',
  1123. });
  1124. }
  1125. async function step6SwitchToOneTimeCodeLogin(snapshot) {
  1126. const switchTrigger = snapshot?.switchTrigger || findOneTimeCodeLoginTrigger();
  1127. if (!switchTrigger || !isActionEnabled(switchTrigger)) {
  1128. return createStep6RecoverableResult('missing_one_time_code_trigger', inspectLoginAuthState(), {
  1129. message: '当前登录页没有可用的一次性验证码登录入口。',
  1130. });
  1131. }
  1132. log('步骤 6:已检测到一次性验证码登录入口,准备切换...');
  1133. const loginVerificationRequestedAt = Date.now();
  1134. await humanPause(350, 900);
  1135. simulateClick(switchTrigger);
  1136. log('步骤 6:已点击一次性验证码登录');
  1137. await sleep(1200);
  1138. return waitForStep6SwitchTransition(loginVerificationRequestedAt);
  1139. }
  1140. async function step6LoginFromPasswordPage(payload, snapshot) {
  1141. const currentSnapshot = snapshot || inspectLoginAuthState();
  1142. if (currentSnapshot.passwordInput) {
  1143. if (!payload.password) {
  1144. throw new Error('登录时缺少密码,步骤 6 无法继续。');
  1145. }
  1146. log('步骤 6:已进入密码页,准备填写密码...');
  1147. await humanPause(550, 1450);
  1148. fillInput(currentSnapshot.passwordInput, payload.password);
  1149. log('步骤 6:已填写密码');
  1150. await sleep(500);
  1151. const passwordSubmittedAt = Date.now();
  1152. await triggerLoginSubmitAction(currentSnapshot.submitButton, currentSnapshot.passwordInput);
  1153. log('步骤 6:已提交密码');
  1154. const transition = await waitForStep6PasswordSubmitTransition(passwordSubmittedAt);
  1155. if (transition.action === 'done') {
  1156. log('步骤 6:已进入登录验证码页面。', 'ok');
  1157. return transition.result;
  1158. }
  1159. if (transition.action === 'recoverable') {
  1160. log(`步骤 6:${transition.result.message || '提交密码后仍未进入登录验证码页面,准备重新执行步骤 6。'}`, 'warn');
  1161. return transition.result;
  1162. }
  1163. if (transition.action === 'switch') {
  1164. return step6SwitchToOneTimeCodeLogin(transition.snapshot);
  1165. }
  1166. return createStep6RecoverableResult('password_submit_unknown', inspectLoginAuthState(), {
  1167. message: '提交密码后未得到可用的下一步状态。',
  1168. });
  1169. }
  1170. if (currentSnapshot.switchTrigger) {
  1171. return step6SwitchToOneTimeCodeLogin(currentSnapshot);
  1172. }
  1173. return createStep6RecoverableResult('password_page_unactionable', currentSnapshot, {
  1174. message: '当前停留在登录页,但没有可提交密码的输入框,也没有一次性验证码登录入口。',
  1175. });
  1176. }
  1177. async function step6LoginFromEmailPage(payload, snapshot) {
  1178. const currentSnapshot = snapshot || inspectLoginAuthState();
  1179. const emailInput = currentSnapshot.emailInput || getLoginEmailInput();
  1180. if (!emailInput) {
  1181. throw new Error('在登录页未找到邮箱输入框。URL: ' + location.href);
  1182. }
  1183. if ((emailInput.value || '').trim() !== payload.email) {
  1184. await humanPause(500, 1400);
  1185. fillInput(emailInput, payload.email);
  1186. log('步骤 6:已填写邮箱');
  1187. } else {
  1188. log('步骤 6:邮箱已在输入框中,准备提交...');
  1189. }
  1190. await sleep(500);
  1191. const emailSubmittedAt = Date.now();
  1192. await triggerLoginSubmitAction(currentSnapshot.submitButton, emailInput);
  1193. log('步骤 6:已提交邮箱');
  1194. const transition = await waitForStep6EmailSubmitTransition(emailSubmittedAt);
  1195. if (transition.action === 'done') {
  1196. log('步骤 6:已进入登录验证码页面。', 'ok');
  1197. return transition.result;
  1198. }
  1199. if (transition.action === 'recoverable') {
  1200. log(`步骤 6:${transition.result.message || '提交邮箱后仍未进入目标页面,准备重新执行步骤 6。'}`, 'warn');
  1201. return transition.result;
  1202. }
  1203. if (transition.action === 'password') {
  1204. return step6LoginFromPasswordPage(payload, transition.snapshot);
  1205. }
  1206. return createStep6RecoverableResult('email_submit_unknown', inspectLoginAuthState(), {
  1207. message: '提交邮箱后未得到可用的下一步状态。',
  1208. });
  1209. }
  1210. async function step6_login(payload) {
  1211. const { email } = payload;
  1212. if (!email) throw new Error('登录时缺少邮箱地址。');
  1213. log(`步骤 6:正在使用 ${email} 登录...`);
  1214. const snapshot = await waitForKnownLoginAuthState(15000);
  1215. if (snapshot.state === 'verification_page') {
  1216. log('步骤 6:登录验证码页面已就绪。', 'ok');
  1217. return createStep6SuccessResult(snapshot, { via: 'already_on_verification_page' });
  1218. }
  1219. if (snapshot.state === 'login_timeout_error_page') {
  1220. log('步骤 6:检测到登录超时报错,准备重新执行步骤 6。', 'warn');
  1221. return createStep6RecoverableResult('login_timeout_error_page', snapshot, {
  1222. message: '当前页面处于登录超时报错页。',
  1223. });
  1224. }
  1225. if (snapshot.state === 'email_page') {
  1226. return step6LoginFromEmailPage(payload, snapshot);
  1227. }
  1228. if (snapshot.state === 'password_page') {
  1229. return step6LoginFromPasswordPage(payload, snapshot);
  1230. }
  1231. throwForStep6FatalState(snapshot);
  1232. throw new Error(`无法识别当前登录页面状态。URL: ${snapshot?.url || location.href}`);
  1233. }
  1234. // ============================================================
  1235. // Step 8: Find "继续" on OAuth consent page for debugger click
  1236. // ============================================================
  1237. // After login + verification, page shows:
  1238. // "使用 ChatGPT 登录到 Codex" with a "继续" submit button.
  1239. // Background performs the actual click through the debugger Input API.
  1240. async function step8_findAndClick() {
  1241. log('步骤 8:正在查找 OAuth 同意页的“继续”按钮...');
  1242. const continueBtn = await prepareStep8ContinueButton();
  1243. const rect = getSerializableRect(continueBtn);
  1244. log('步骤 8:已找到“继续”按钮并准备好调试器点击坐标。');
  1245. return {
  1246. rect,
  1247. buttonText: (continueBtn.textContent || '').trim(),
  1248. url: location.href,
  1249. };
  1250. }
  1251. function getStep8State() {
  1252. const continueBtn = getPrimaryContinueButton();
  1253. const state = {
  1254. url: location.href,
  1255. consentPage: isOAuthConsentPage(),
  1256. consentReady: isStep8Ready(),
  1257. verificationPage: isVerificationPageStillVisible(),
  1258. addPhonePage: isAddPhonePageReady(),
  1259. buttonFound: Boolean(continueBtn),
  1260. buttonEnabled: isButtonEnabled(continueBtn),
  1261. buttonText: continueBtn ? getActionText(continueBtn) : '',
  1262. };
  1263. if (continueBtn) {
  1264. try {
  1265. state.rect = getSerializableRect(continueBtn);
  1266. } catch {
  1267. state.rect = null;
  1268. }
  1269. }
  1270. return state;
  1271. }
  1272. async function step8_triggerContinue(payload = {}) {
  1273. const strategy = payload?.strategy || 'requestSubmit';
  1274. const continueBtn = await prepareStep8ContinueButton({
  1275. findTimeoutMs: payload?.findTimeoutMs,
  1276. enabledTimeoutMs: payload?.enabledTimeoutMs,
  1277. });
  1278. const form = continueBtn.form || continueBtn.closest('form');
  1279. switch (strategy) {
  1280. case 'requestSubmit':
  1281. if (!form || typeof form.requestSubmit !== 'function') {
  1282. throw new Error('“继续”按钮当前不在可提交的 form 中,无法使用 requestSubmit。URL: ' + location.href);
  1283. }
  1284. form.requestSubmit(continueBtn);
  1285. break;
  1286. case 'nativeClick':
  1287. continueBtn.click();
  1288. break;
  1289. case 'dispatchClick':
  1290. simulateClick(continueBtn);
  1291. break;
  1292. default:
  1293. throw new Error(`未知的 Step 8 触发策略:${strategy}`);
  1294. }
  1295. log(`Step 8: continue button triggered via ${strategy}.`);
  1296. return {
  1297. strategy,
  1298. ...getStep8State(),
  1299. };
  1300. }
  1301. async function prepareStep8ContinueButton(options = {}) {
  1302. const {
  1303. findTimeoutMs = 10000,
  1304. enabledTimeoutMs = 8000,
  1305. } = options;
  1306. const continueBtn = await findContinueButton(findTimeoutMs);
  1307. await waitForButtonEnabled(continueBtn, enabledTimeoutMs);
  1308. await humanPause(250, 700);
  1309. continueBtn.scrollIntoView({ behavior: 'auto', block: 'center' });
  1310. continueBtn.focus();
  1311. await waitForStableButtonRect(continueBtn);
  1312. return continueBtn;
  1313. }
  1314. async function findContinueButton(timeout = 10000) {
  1315. const start = Date.now();
  1316. while (Date.now() - start < timeout) {
  1317. throwIfStopped();
  1318. if (isAddPhonePageReady()) {
  1319. throw new Error('当前页面已进入手机号页面,不是 OAuth 授权同意页。URL: ' + location.href);
  1320. }
  1321. const button = getPrimaryContinueButton();
  1322. if (button && isStep8Ready()) {
  1323. return button;
  1324. }
  1325. await sleep(150);
  1326. }
  1327. throw new Error('在 OAuth 同意页未找到“继续”按钮,或页面尚未进入授权同意状态。URL: ' + location.href);
  1328. }
  1329. async function waitForButtonEnabled(button, timeout = 8000) {
  1330. const start = Date.now();
  1331. while (Date.now() - start < timeout) {
  1332. throwIfStopped();
  1333. if (isButtonEnabled(button)) return;
  1334. await sleep(150);
  1335. }
  1336. throw new Error('“继续”按钮长时间不可点击。URL: ' + location.href);
  1337. }
  1338. function isButtonEnabled(button) {
  1339. return Boolean(button)
  1340. && !button.disabled
  1341. && button.getAttribute('aria-disabled') !== 'true';
  1342. }
  1343. async function waitForStableButtonRect(button, timeout = 1500) {
  1344. let previous = null;
  1345. let stableSamples = 0;
  1346. const start = Date.now();
  1347. while (Date.now() - start < timeout) {
  1348. throwIfStopped();
  1349. const rect = button?.getBoundingClientRect?.();
  1350. if (rect && rect.width > 0 && rect.height > 0) {
  1351. const snapshot = {
  1352. left: rect.left,
  1353. top: rect.top,
  1354. width: rect.width,
  1355. height: rect.height,
  1356. };
  1357. if (
  1358. previous
  1359. && Math.abs(snapshot.left - previous.left) < 1
  1360. && Math.abs(snapshot.top - previous.top) < 1
  1361. && Math.abs(snapshot.width - previous.width) < 1
  1362. && Math.abs(snapshot.height - previous.height) < 1
  1363. ) {
  1364. stableSamples += 1;
  1365. if (stableSamples >= 2) {
  1366. return;
  1367. }
  1368. } else {
  1369. stableSamples = 0;
  1370. }
  1371. previous = snapshot;
  1372. }
  1373. await sleep(80);
  1374. }
  1375. }
  1376. function getSerializableRect(el) {
  1377. const rect = el.getBoundingClientRect();
  1378. if (!rect.width || !rect.height) {
  1379. throw new Error('滚动后“继续”按钮没有可点击尺寸。URL: ' + location.href);
  1380. }
  1381. return {
  1382. left: rect.left,
  1383. top: rect.top,
  1384. width: rect.width,
  1385. height: rect.height,
  1386. centerX: rect.left + (rect.width / 2),
  1387. centerY: rect.top + (rect.height / 2),
  1388. };
  1389. }
  1390. // ============================================================
  1391. // Step 5: Fill Name & Birthday / Age
  1392. // ============================================================
  1393. async function step5_fillNameBirthday(payload) {
  1394. const { firstName, lastName, age, year, month, day } = payload;
  1395. if (!firstName || !lastName) throw new Error('未提供姓名数据。');
  1396. const resolvedAge = age ?? (year ? new Date().getFullYear() - Number(year) : null);
  1397. const hasBirthdayData = [year, month, day].every(value => value != null && !Number.isNaN(Number(value)));
  1398. if (!hasBirthdayData && (resolvedAge == null || Number.isNaN(Number(resolvedAge)))) {
  1399. throw new Error('未提供生日或年龄数据。');
  1400. }
  1401. const fullName = `${firstName} ${lastName}`;
  1402. log(`步骤 5:正在填写姓名:${fullName}`);
  1403. // Actual DOM structure:
  1404. // - Full name: <input name="name" placeholder="全名" type="text">
  1405. // - Birthday: React Aria DateField or hidden input[name="birthday"]
  1406. // - Age: <input name="age" type="text|number">
  1407. // --- Full Name (single field, not first+last) ---
  1408. let nameInput = null;
  1409. try {
  1410. nameInput = await waitForElement(
  1411. 'input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]',
  1412. 10000
  1413. );
  1414. } catch {
  1415. throw new Error('未找到姓名输入框。URL: ' + location.href);
  1416. }
  1417. await humanPause(500, 1300);
  1418. fillInput(nameInput, fullName);
  1419. log(`步骤 5:姓名已填写:${fullName}`);
  1420. let birthdayMode = false;
  1421. let ageInput = null;
  1422. let yearSpinner = null;
  1423. let monthSpinner = null;
  1424. let daySpinner = null;
  1425. let hiddenBirthday = null;
  1426. let yearReactSelect = null;
  1427. let monthReactSelect = null;
  1428. let dayReactSelect = null;
  1429. let visibleAgeInput = false;
  1430. let visibleBirthdaySpinners = false;
  1431. let visibleBirthdaySelects = false;
  1432. for (let i = 0; i < 100; i++) {
  1433. yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  1434. monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  1435. daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  1436. hiddenBirthday = document.querySelector('input[name="birthday"]');
  1437. ageInput = document.querySelector('input[name="age"]');
  1438. yearReactSelect = findBirthdayReactAriaSelect('年');
  1439. monthReactSelect = findBirthdayReactAriaSelect('月');
  1440. dayReactSelect = findBirthdayReactAriaSelect('天');
  1441. visibleAgeInput = Boolean(ageInput && isVisibleElement(ageInput));
  1442. visibleBirthdaySpinners = Boolean(
  1443. yearSpinner
  1444. && monthSpinner
  1445. && daySpinner
  1446. && isVisibleElement(yearSpinner)
  1447. && isVisibleElement(monthSpinner)
  1448. && isVisibleElement(daySpinner)
  1449. );
  1450. visibleBirthdaySelects = Boolean(
  1451. yearReactSelect?.button
  1452. && monthReactSelect?.button
  1453. && dayReactSelect?.button
  1454. && isVisibleElement(yearReactSelect.button)
  1455. && isVisibleElement(monthReactSelect.button)
  1456. && isVisibleElement(dayReactSelect.button)
  1457. );
  1458. if (visibleAgeInput) break;
  1459. if (visibleBirthdaySpinners || visibleBirthdaySelects) {
  1460. birthdayMode = true;
  1461. break;
  1462. }
  1463. await sleep(100);
  1464. }
  1465. if (birthdayMode) {
  1466. if (!hasBirthdayData) {
  1467. throw new Error('检测到生日字段,但未提供生日数据。');
  1468. }
  1469. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  1470. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  1471. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  1472. const yearReactSelect = findBirthdayReactAriaSelect('年');
  1473. const monthReactSelect = findBirthdayReactAriaSelect('月');
  1474. const dayReactSelect = findBirthdayReactAriaSelect('天');
  1475. if (yearReactSelect?.nativeSelect && monthReactSelect?.nativeSelect && dayReactSelect?.nativeSelect) {
  1476. const desiredDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1477. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1478. log('步骤 5:检测到 React Aria 下拉生日字段,正在填写生日...');
  1479. await humanPause(450, 1100);
  1480. await setReactAriaBirthdaySelect(yearReactSelect, year);
  1481. await humanPause(250, 650);
  1482. await setReactAriaBirthdaySelect(monthReactSelect, month);
  1483. await humanPause(250, 650);
  1484. await setReactAriaBirthdaySelect(dayReactSelect, day);
  1485. if (hiddenBirthday) {
  1486. const start = Date.now();
  1487. while (Date.now() - start < 2000) {
  1488. if ((hiddenBirthday.value || '') === desiredDate) break;
  1489. await sleep(100);
  1490. }
  1491. if ((hiddenBirthday.value || '') !== desiredDate) {
  1492. throw new Error(`生日值未成功写入页面。期望 ${desiredDate},实际 ${(hiddenBirthday.value || '空')}。`);
  1493. }
  1494. }
  1495. log(`步骤 5:React Aria 生日已填写:${desiredDate}`);
  1496. }
  1497. if (yearSpinner && monthSpinner && daySpinner) {
  1498. log('步骤 5:检测到生日字段,正在填写生日...');
  1499. async function setSpinButton(el, value) {
  1500. el.focus();
  1501. await sleep(100);
  1502. document.execCommand('selectAll', false, null);
  1503. await sleep(50);
  1504. const valueStr = String(value);
  1505. for (const char of valueStr) {
  1506. el.dispatchEvent(new KeyboardEvent('keydown', { key: char, code: `Digit${char}`, bubbles: true }));
  1507. el.dispatchEvent(new KeyboardEvent('keypress', { key: char, code: `Digit${char}`, bubbles: true }));
  1508. el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: char, bubbles: true }));
  1509. el.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: char, bubbles: true }));
  1510. await sleep(50);
  1511. }
  1512. el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab', code: 'Tab', bubbles: true }));
  1513. el.blur();
  1514. await sleep(100);
  1515. }
  1516. await humanPause(450, 1100);
  1517. await setSpinButton(yearSpinner, year);
  1518. await humanPause(250, 650);
  1519. await setSpinButton(monthSpinner, String(month).padStart(2, '0'));
  1520. await humanPause(250, 650);
  1521. await setSpinButton(daySpinner, String(day).padStart(2, '0'));
  1522. log(`步骤 5:生日已填写:${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
  1523. }
  1524. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1525. if (hiddenBirthday) {
  1526. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1527. hiddenBirthday.value = dateStr;
  1528. hiddenBirthday.dispatchEvent(new Event('input', { bubbles: true }));
  1529. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  1530. log(`步骤 5:已设置隐藏生日输入框:${dateStr}`);
  1531. }
  1532. } else if (ageInput) {
  1533. if (resolvedAge == null || Number.isNaN(Number(resolvedAge))) {
  1534. throw new Error('检测到年龄字段,但未提供年龄数据。');
  1535. }
  1536. await humanPause(500, 1300);
  1537. fillInput(ageInput, String(resolvedAge));
  1538. log(`步骤 5:年龄已填写:${resolvedAge}`);
  1539. } else {
  1540. throw new Error('未找到生日或年龄输入项。URL: ' + location.href);
  1541. }
  1542. // Click "完成帐户创建" button
  1543. await sleep(500);
  1544. const completeBtn = document.querySelector('button[type="submit"]')
  1545. || await waitForElementByText('button', /完成|create|continue|finish|done|agree/i, 5000).catch(() => null);
  1546. if (!completeBtn) {
  1547. throw new Error('未找到“完成帐户创建”按钮。URL: ' + location.href);
  1548. }
  1549. await humanPause(500, 1300);
  1550. simulateClick(completeBtn);
  1551. log('步骤 5:已点击“完成帐户创建”,正在等待页面结果...');
  1552. const outcome = await waitForStep5SubmitOutcome();
  1553. if (outcome.invalidProfile) {
  1554. throw new Error(`步骤 5:${outcome.errorText}`);
  1555. }
  1556. log(`步骤 5:资料已通过。`, 'ok');
  1557. reportComplete(5, { addPhonePage: Boolean(outcome.addPhonePage) });
  1558. }