signup-page.js 45 KB

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