signup-page.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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 (message.type === 'EXECUTE_STEP' || message.type === 'FILL_CODE' || message.type === 'STEP8_FIND_AND_CLICK' || message.type === 'CLICK_RESEND_EMAIL' || message.type === 'HANDLE_ABOUT_YOU') {
  7. resetStopState();
  8. handleCommand(message).then((result) => {
  9. sendResponse({ ok: true, ...(result || {}) });
  10. }).catch(err => {
  11. if (isStopError(err)) {
  12. log(`Step ${message.step || 8}: Stopped by user.`, 'warn');
  13. sendResponse({ stopped: true, error: err.message });
  14. return;
  15. }
  16. if (message.type === 'STEP8_FIND_AND_CLICK') {
  17. log(`Step 8: ${err.message}`, 'error');
  18. sendResponse({ error: err.message });
  19. return;
  20. }
  21. reportError(message.step, err.message);
  22. sendResponse({ error: err.message });
  23. });
  24. return true;
  25. }
  26. });
  27. async function handleCommand(message) {
  28. switch (message.type) {
  29. case 'EXECUTE_STEP':
  30. switch (message.step) {
  31. case 2: return await step2_clickRegister();
  32. case 3: return await step3_fillEmailPassword(message.payload);
  33. case 5: return await step5_fillNameBirthday(message.payload);
  34. case 6: return await step6_login(message.payload);
  35. case 8: return await step8_findAndClick();
  36. default: throw new Error(`signup-page.js does not handle step ${message.step}`);
  37. }
  38. case 'FILL_CODE':
  39. // Step 4 = signup code, Step 7 = login code (same handler)
  40. return await fillVerificationCode(message.step, message.payload);
  41. case 'CLICK_RESEND_EMAIL':
  42. return await clickResendEmail(message.step);
  43. case 'STEP8_FIND_AND_CLICK':
  44. return await step8_findAndClick();
  45. case 'HANDLE_ABOUT_YOU':
  46. return await handleAboutYouPage(message.payload);
  47. }
  48. }
  49. // ============================================================
  50. // Step 2: Click Register
  51. // ============================================================
  52. async function step2_clickRegister() {
  53. log('Step 2: Looking for Register/Sign up button...');
  54. let registerBtn = null;
  55. try {
  56. registerBtn = await waitForElementByText(
  57. 'a, button, [role="button"], [role="link"]',
  58. /sign\s*up|register|create\s*account|注册/i,
  59. 10000
  60. );
  61. } catch {
  62. // Some pages may have a direct link
  63. try {
  64. registerBtn = await waitForElement('a[href*="signup"], a[href*="register"]', 5000);
  65. } catch {
  66. throw new Error(
  67. 'Could not find Register/Sign up button. ' +
  68. 'Check auth page DOM in DevTools. URL: ' + location.href
  69. );
  70. }
  71. }
  72. await humanPause(450, 1200);
  73. simulateClick(registerBtn);
  74. log('Step 2: Clicked Register button');
  75. // Don't mark step 2 complete until the signup form is actually reachable.
  76. // This avoids auto-run racing ahead while a human-verification challenge
  77. // or page transition is still in progress.
  78. try {
  79. await waitForElement(
  80. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email"], input[placeholder*="Email"]',
  81. 30000
  82. );
  83. log('Step 2: Signup form is ready after human verification/page transition');
  84. } catch {
  85. // Fallback: some auth pages may delay rendering, but URL/path has already moved on.
  86. if (/signup|register|email|continue/i.test(location.href)) {
  87. log('Step 2: Signup page transition detected, proceeding', 'warn');
  88. } else {
  89. throw new Error('Register clicked, but signup form did not become ready after 30s. Human verification may still be pending. URL: ' + location.href);
  90. }
  91. }
  92. reportComplete(2);
  93. }
  94. // ============================================================
  95. // Step 3: Fill Email & Password
  96. // ============================================================
  97. async function step3_fillEmailPassword(payload) {
  98. const { email } = payload;
  99. if (!email) throw new Error('No email provided. Paste email in Side Panel first.');
  100. log(`Step 3: Filling email: ${email}`);
  101. // Find email input
  102. let emailInput = null;
  103. try {
  104. emailInput = await waitForElement(
  105. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email"], input[placeholder*="Email"]',
  106. 10000
  107. );
  108. } catch {
  109. throw new Error('Could not find email input field on signup page. URL: ' + location.href);
  110. }
  111. await humanPause(500, 1400);
  112. fillInput(emailInput, email);
  113. log('Step 3: Email filled');
  114. // Check if password field is on the same page
  115. let passwordInput = document.querySelector('input[type="password"]');
  116. if (!passwordInput) {
  117. // Need to submit email first to get to password page
  118. log('Step 3: No password field yet, submitting email first...');
  119. const submitBtn = document.querySelector('button[type="submit"]')
  120. || await waitForElementByText('button', /continue|next|submit|继续|下一步/i, 5000).catch(() => null);
  121. if (submitBtn) {
  122. await humanPause(400, 1100);
  123. simulateClick(submitBtn);
  124. log('Step 3: Submitted email, waiting for password field...');
  125. await sleep(2000);
  126. }
  127. try {
  128. passwordInput = await waitForElement('input[type="password"]', 10000);
  129. } catch {
  130. throw new Error('Could not find password input after submitting email. URL: ' + location.href);
  131. }
  132. }
  133. if (!payload.password) throw new Error('No password provided. Step 3 requires a generated password.');
  134. await humanPause(600, 1500);
  135. fillInput(passwordInput, payload.password);
  136. log('Step 3: Password filled');
  137. // Report complete BEFORE submit, because submit causes page navigation
  138. // which kills the content script connection
  139. reportComplete(3, { email });
  140. // Submit the form (page will navigate away after this)
  141. await sleep(500);
  142. const submitBtn = document.querySelector('button[type="submit"]')
  143. || await waitForElementByText('button', /continue|sign\s*up|submit|注册|创建|create/i, 5000).catch(() => null);
  144. if (submitBtn) {
  145. await humanPause(500, 1300);
  146. simulateClick(submitBtn);
  147. log('Step 3: Form submitted');
  148. }
  149. }
  150. // ============================================================
  151. // Click "重新发送电子邮件" (used before step 4 and step 7 polling)
  152. // ============================================================
  153. async function clickResendEmail(step) {
  154. log(`Step ${step}: Looking for "重新发送电子邮件" button...`);
  155. let resendBtn = null;
  156. try {
  157. resendBtn = await waitForElementByText(
  158. 'a, button, [role="button"], [role="link"], span',
  159. /重新发送电子邮件|resend\s*email/i,
  160. 10000
  161. );
  162. } catch {
  163. log(`Step ${step}: "重新发送电子邮件" button not found, skipping`, 'warn');
  164. return;
  165. }
  166. // Prevent parent form POST submission (Remix/React Router route without action)
  167. const parentForm = resendBtn.closest('form');
  168. const blockSubmit = (e) => e.preventDefault();
  169. if (parentForm) parentForm.addEventListener('submit', blockSubmit, { once: true });
  170. await humanPause(400, 1000);
  171. resendBtn.click();
  172. log(`Step ${step}: Clicked "重新发送电子邮件"`, 'ok');
  173. await sleep(2000);
  174. if (parentForm) parentForm.removeEventListener('submit', blockSubmit);
  175. }
  176. // ============================================================
  177. // Fill Verification Code (used by step 4 and step 7)
  178. // ============================================================
  179. async function fillVerificationCode(step, payload) {
  180. const { code } = payload;
  181. if (!code) throw new Error('No verification code provided.');
  182. log(`Step ${step}: Filling verification code: ${code}`);
  183. // Find code input — could be a single input or multiple separate inputs
  184. let codeInput = null;
  185. try {
  186. codeInput = await waitForElement(
  187. 'input[name="code"], input[name="otp"], input[type="text"][maxlength="6"], input[aria-label*="code"], input[placeholder*="code"], input[placeholder*="Code"], input[inputmode="numeric"]',
  188. 10000
  189. );
  190. } catch {
  191. // Check for multiple single-digit inputs (common pattern)
  192. const singleInputs = document.querySelectorAll('input[maxlength="1"]');
  193. if (singleInputs.length >= 6) {
  194. log(`Step ${step}: Found single-digit code inputs, filling individually...`);
  195. for (let i = 0; i < 6 && i < singleInputs.length; i++) {
  196. fillInput(singleInputs[i], code[i]);
  197. await sleep(100);
  198. }
  199. await sleep(1000);
  200. // Verify page navigated away from verification page
  201. await verifyCodeAccepted(step);
  202. reportComplete(step);
  203. return;
  204. }
  205. throw new Error('Could not find verification code input. URL: ' + location.href);
  206. }
  207. fillInput(codeInput, code);
  208. log(`Step ${step}: Code filled`);
  209. // Submit
  210. await sleep(500);
  211. const submitBtn = document.querySelector('button[type="submit"]')
  212. || await waitForElementByText('button', /verify|confirm|submit|continue|确认|验证|继续/i, 5000).catch(() => null);
  213. if (submitBtn) {
  214. await humanPause(450, 1200);
  215. simulateClick(submitBtn);
  216. log(`Step ${step}: Verification submitted`);
  217. }
  218. // Wait and verify the page actually moved past the verification page
  219. await verifyCodeAccepted(step);
  220. reportComplete(step);
  221. }
  222. function hasVisibleVerificationInputs() {
  223. const singleInputs = Array.from(document.querySelectorAll('input[maxlength="1"]'))
  224. .filter(isElementVisible);
  225. if (singleInputs.length >= 6) return true;
  226. const selectors = [
  227. 'input[name="code"]',
  228. 'input[name="otp"]',
  229. 'input[type="text"][maxlength="6"]',
  230. 'input[aria-label*="code" i]',
  231. 'input[placeholder*="code" i]',
  232. 'input[inputmode="numeric"]',
  233. ];
  234. return selectors.some(selector => Array.from(document.querySelectorAll(selector)).some(isElementVisible));
  235. }
  236. function hasPostVerificationSignals() {
  237. const currentPath = location.pathname;
  238. if (currentPath.includes('/about-you')) return true;
  239. const nextStepSelectors = [
  240. 'input[name="name"]',
  241. 'input[autocomplete="name"]',
  242. 'input[name="birthday"]',
  243. '[role="spinbutton"][data-type="year"]',
  244. 'button[data-testid*="continue"]',
  245. ];
  246. if (nextStepSelectors.some(selector => Array.from(document.querySelectorAll(selector)).some(isElementVisible))) {
  247. return true;
  248. }
  249. const pageText = (document.body?.innerText || '').slice(0, 4000).toLowerCase();
  250. return (
  251. pageText.includes('使用 chatgpt 登录到 codex')
  252. || pageText.includes('continue to codex')
  253. || pageText.includes('consent')
  254. || pageText.includes('生日')
  255. || pageText.includes('full name')
  256. );
  257. }
  258. async function verifyCodeAccepted(step, timeout = 15000) {
  259. const start = Date.now();
  260. const verificationPaths = ['/email-verification', '/verify', '/otp'];
  261. while (Date.now() - start < timeout) {
  262. throwIfStopped();
  263. const currentPath = location.pathname;
  264. const stillOnVerification = verificationPaths.some(p => currentPath.includes(p));
  265. const verificationInputsVisible = hasVisibleVerificationInputs();
  266. const postVerificationSignals = hasPostVerificationSignals();
  267. if (!stillOnVerification || (!verificationInputsVisible && postVerificationSignals)) {
  268. log(`Step ${step}: Verification code accepted, page navigated to ${currentPath}`);
  269. return;
  270. }
  271. // Check for error messages on the page (wrong code)
  272. const errorEl = document.querySelector('[class*="error"], [class*="Error"], [role="alert"]');
  273. if (errorEl) {
  274. const errorText = (errorEl.textContent || '').trim();
  275. if (errorText && errorText.length < 200) {
  276. throw new Error(`Verification code rejected: ${errorText}. URL: ${location.href}`);
  277. }
  278. }
  279. await sleep(500);
  280. }
  281. // Still on verification page after timeout — code was likely wrong
  282. throw new Error(`Verification code ${step === 4 ? 'signup' : 'login'} was not accepted (page did not navigate). URL: ${location.href}`);
  283. }
  284. // ============================================================
  285. // Step 6: Login with registered account (on OAuth auth page)
  286. // ============================================================
  287. async function step6_login(payload) {
  288. const { email, password } = payload;
  289. if (!email) throw new Error('No email provided for login.');
  290. log(`Step 6: Logging in with ${email}...`);
  291. // Wait for email input on the auth page
  292. let emailInput = null;
  293. try {
  294. emailInput = await waitForElement(
  295. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email" i], input[placeholder*="Email"]',
  296. 15000
  297. );
  298. } catch {
  299. throw new Error('Could not find email input on login page. URL: ' + location.href);
  300. }
  301. await humanPause(500, 1400);
  302. fillInput(emailInput, email);
  303. log('Step 6: Email filled');
  304. // Submit email
  305. await sleep(500);
  306. const submitBtn1 = document.querySelector('button[type="submit"]')
  307. || await waitForElementByText('button', /continue|next|submit|继续|下一步/i, 5000).catch(() => null);
  308. if (submitBtn1) {
  309. await humanPause(400, 1100);
  310. simulateClick(submitBtn1);
  311. log('Step 6: Submitted email');
  312. }
  313. const passwordInput = await waitForLoginPasswordField();
  314. if (passwordInput) {
  315. log('Step 6: Password field found, filling password...');
  316. await humanPause(550, 1450);
  317. fillInput(passwordInput, password);
  318. await sleep(500);
  319. const submitBtn2 = document.querySelector('button[type="submit"]')
  320. || await waitForElementByText('button', /continue|log\s*in|submit|sign\s*in|登录|继续/i, 5000).catch(() => null);
  321. // Report complete BEFORE submit in case page navigates
  322. reportComplete(6, { needsOTP: true });
  323. if (submitBtn2) {
  324. await humanPause(450, 1200);
  325. simulateClick(submitBtn2);
  326. log('Step 6: Submitted password, may need verification code (step 7)');
  327. }
  328. return;
  329. }
  330. // No password field — OTP flow
  331. log('Step 6: No password field. OTP flow or auto-redirect.');
  332. reportComplete(6, { needsOTP: true });
  333. }
  334. async function waitForLoginPasswordField(timeout = 25000) {
  335. const start = Date.now();
  336. while (Date.now() - start < timeout) {
  337. throwIfStopped();
  338. const passwordInput = findVisiblePasswordInput();
  339. if (passwordInput) {
  340. return passwordInput;
  341. }
  342. await sleep(250);
  343. }
  344. log(`Step 6: Password field did not appear within ${Math.round(timeout / 1000)}s.`, 'warn');
  345. return null;
  346. }
  347. function findVisiblePasswordInput() {
  348. const inputs = document.querySelectorAll('input[type="password"]');
  349. for (const input of inputs) {
  350. if (isElementVisible(input)) {
  351. return input;
  352. }
  353. }
  354. return null;
  355. }
  356. function isElementVisible(el) {
  357. if (!el) return false;
  358. const style = window.getComputedStyle(el);
  359. if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
  360. return false;
  361. }
  362. const rect = el.getBoundingClientRect();
  363. return rect.width > 0 && rect.height > 0;
  364. }
  365. // ============================================================
  366. // Step 8: Find "继续" on OAuth consent page for debugger click
  367. // ============================================================
  368. // After login + verification, page shows:
  369. // "使用 ChatGPT 登录到 Codex" with a "继续" submit button.
  370. // Background performs the actual click through the debugger Input API.
  371. async function step8_findAndClick() {
  372. log('Step 8: Looking for OAuth consent "继续" button...');
  373. const continueBtn = await findContinueButton();
  374. await waitForButtonEnabled(continueBtn);
  375. await humanPause(350, 900);
  376. continueBtn.scrollIntoView({ behavior: 'smooth', block: 'center' });
  377. continueBtn.focus();
  378. await sleep(250);
  379. // Click using native .click() — more reliable than synthetic MouseEvent for trusted forms
  380. continueBtn.click();
  381. log('Step 8: Clicked "继续" button via .click()', 'ok');
  382. // Fallback: if the button is inside a form, also try submitting the form directly
  383. await sleep(2000);
  384. const form = continueBtn.closest('form');
  385. if (form && location.href.includes('authorize')) {
  386. log('Step 8: Also submitting parent form as fallback...');
  387. form.requestSubmit ? form.requestSubmit(continueBtn) : form.submit();
  388. }
  389. return {
  390. clicked: true,
  391. buttonText: (continueBtn.textContent || '').trim(),
  392. url: location.href,
  393. };
  394. }
  395. async function findContinueButton() {
  396. try {
  397. return await waitForElement(
  398. 'button[type="submit"][data-dd-action-name="Continue"], button[type="submit"]._primary_3rdp0_107',
  399. 10000
  400. );
  401. } catch {
  402. try {
  403. return await waitForElementByText('button', /继续|Continue/, 5000);
  404. } catch {
  405. throw new Error('Could not find "继续" button on OAuth consent page. URL: ' + location.href);
  406. }
  407. }
  408. }
  409. async function waitForButtonEnabled(button, timeout = 8000) {
  410. const start = Date.now();
  411. while (Date.now() - start < timeout) {
  412. throwIfStopped();
  413. if (isButtonEnabled(button)) return;
  414. await sleep(150);
  415. }
  416. throw new Error('"继续" button stayed disabled for too long. URL: ' + location.href);
  417. }
  418. function isButtonEnabled(button) {
  419. return Boolean(button)
  420. && !button.disabled
  421. && button.getAttribute('aria-disabled') !== 'true';
  422. }
  423. function getSerializableRect(el) {
  424. const rect = el.getBoundingClientRect();
  425. if (!rect.width || !rect.height) {
  426. throw new Error('"继续" button has no clickable size after scrolling. URL: ' + location.href);
  427. }
  428. return {
  429. left: rect.left,
  430. top: rect.top,
  431. width: rect.width,
  432. height: rect.height,
  433. centerX: rect.left + (rect.width / 2),
  434. centerY: rect.top + (rect.height / 2),
  435. };
  436. }
  437. // ============================================================
  438. // Handle /about-you page (appears after login if birthday was missing)
  439. // ============================================================
  440. async function handleAboutYouPage(payload) {
  441. if (!location.href.includes('/about-you')) {
  442. return { handled: false };
  443. }
  444. log('Detected /about-you page, filling birthday info...');
  445. const { year, month, day, fullName } = payload || {};
  446. if (!year || !month || !day) {
  447. throw new Error('No birthday data available for about-you page.');
  448. }
  449. // Wait for the page to fully load
  450. await sleep(1000);
  451. // Fill name if present and empty
  452. const nameInput = document.querySelector('input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]');
  453. if (nameInput && !nameInput.value && fullName) {
  454. fillInput(nameInput, fullName);
  455. log('About-you: Name filled');
  456. await humanPause(300, 800);
  457. }
  458. // Fill birthday using the shared helper
  459. await fillBirthdayFields(year, month, day, 'About-you');
  460. // Click continue/submit button
  461. await sleep(500);
  462. const submitBtn = document.querySelector('button[type="submit"]')
  463. || await waitForElementByText('button', /continue|继续|完成|done|agree|submit/i, 5000).catch(() => null);
  464. if (submitBtn) {
  465. await humanPause(500, 1300);
  466. simulateClick(submitBtn);
  467. log('About-you: Submitted form');
  468. }
  469. return { handled: true };
  470. }
  471. // ============================================================
  472. // Shared birthday filling helper (used by Step 5 and about-you)
  473. // ============================================================
  474. async function fillBirthdayFields(year, month, day, logPrefix) {
  475. const prefix = logPrefix || 'Birthday';
  476. // Strategy 1: React Aria DateField spinbuttons
  477. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  478. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  479. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  480. if (yearSpinner && monthSpinner && daySpinner) {
  481. log(`${prefix}: Filling spinbutton date fields...`);
  482. async function setSpinButton(el, value) {
  483. el.focus();
  484. await sleep(100);
  485. document.execCommand('selectAll', false, null);
  486. await sleep(50);
  487. const valueStr = String(value);
  488. for (const char of valueStr) {
  489. el.dispatchEvent(new KeyboardEvent('keydown', { key: char, code: `Digit${char}`, bubbles: true }));
  490. el.dispatchEvent(new KeyboardEvent('keypress', { key: char, code: `Digit${char}`, bubbles: true }));
  491. el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: char, bubbles: true }));
  492. el.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: char, bubbles: true }));
  493. await sleep(50);
  494. }
  495. el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab', code: 'Tab', bubbles: true }));
  496. el.blur();
  497. await sleep(100);
  498. }
  499. await humanPause(450, 1100);
  500. await setSpinButton(yearSpinner, year);
  501. await humanPause(250, 650);
  502. await setSpinButton(monthSpinner, String(month).padStart(2, '0'));
  503. await humanPause(250, 650);
  504. await setSpinButton(daySpinner, String(day).padStart(2, '0'));
  505. log(`${prefix}: Spinbutton date filled: ${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
  506. return true;
  507. }
  508. // Strategy 2: Select dropdowns (month/day/year)
  509. const selects = document.querySelectorAll('select');
  510. if (selects.length >= 2) {
  511. let monthSelect = null, daySelect = null, yearSelect = null;
  512. for (const sel of selects) {
  513. const name = (sel.name || sel.id || sel.getAttribute('aria-label') || '').toLowerCase();
  514. const opts = Array.from(sel.options).map(o => o.value);
  515. if (name.includes('month') || name.includes('mm')) {
  516. monthSelect = sel;
  517. } else if (name.includes('day') || name.includes('dd')) {
  518. daySelect = sel;
  519. } else if (name.includes('year') || name.includes('yyyy')) {
  520. yearSelect = sel;
  521. } else {
  522. // Heuristic: identify by option count and values
  523. const numericOpts = opts.filter(v => /^\d+$/.test(v));
  524. if (!monthSelect && numericOpts.length >= 12 && numericOpts.length <= 13) {
  525. monthSelect = sel;
  526. } else if (!daySelect && numericOpts.length >= 28 && numericOpts.length <= 32) {
  527. daySelect = sel;
  528. } else if (!yearSelect && numericOpts.some(v => Number(v) > 1900 && Number(v) < 2100)) {
  529. yearSelect = sel;
  530. }
  531. }
  532. }
  533. if (monthSelect || daySelect || yearSelect) {
  534. log(`${prefix}: Filling select dropdown date fields...`);
  535. if (monthSelect) {
  536. setSelectValue(monthSelect, String(month));
  537. await humanPause(200, 500);
  538. }
  539. if (daySelect) {
  540. setSelectValue(daySelect, String(day));
  541. await humanPause(200, 500);
  542. }
  543. if (yearSelect) {
  544. setSelectValue(yearSelect, String(year));
  545. await humanPause(200, 500);
  546. }
  547. log(`${prefix}: Select date filled: ${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
  548. return true;
  549. }
  550. }
  551. // Strategy 3: input[type="date"]
  552. const dateInput = document.querySelector('input[type="date"]');
  553. if (dateInput) {
  554. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  555. const nativeSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
  556. nativeSetter.call(dateInput, dateStr);
  557. dateInput.dispatchEvent(new Event('input', { bubbles: true }));
  558. dateInput.dispatchEvent(new Event('change', { bubbles: true }));
  559. log(`${prefix}: Date input filled: ${dateStr}`);
  560. return true;
  561. }
  562. // Strategy 4: Hidden input[name="birthday"] (fallback)
  563. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  564. if (hiddenBirthday) {
  565. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  566. hiddenBirthday.value = dateStr;
  567. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  568. log(`${prefix}: Hidden birthday input set: ${dateStr}`);
  569. return true;
  570. }
  571. return false;
  572. }
  573. function setSelectValue(selectEl, value) {
  574. // Try exact match first, then try padded value
  575. const candidates = [value, value.padStart(2, '0')];
  576. for (const v of candidates) {
  577. const option = Array.from(selectEl.options).find(o => o.value === v || o.textContent.trim() === v);
  578. if (option) {
  579. selectEl.value = option.value;
  580. selectEl.dispatchEvent(new Event('change', { bubbles: true }));
  581. selectEl.dispatchEvent(new Event('input', { bubbles: true }));
  582. return;
  583. }
  584. }
  585. // Last resort: set by index if value is numeric
  586. const numVal = Number(value);
  587. if (!isNaN(numVal) && numVal > 0 && numVal < selectEl.options.length) {
  588. selectEl.selectedIndex = numVal;
  589. selectEl.dispatchEvent(new Event('change', { bubbles: true }));
  590. selectEl.dispatchEvent(new Event('input', { bubbles: true }));
  591. }
  592. }
  593. // ============================================================
  594. // Step 5: Fill Name & Birthday / Age
  595. // ============================================================
  596. async function step5_fillNameBirthday(payload) {
  597. const { firstName, lastName, age, year, month, day } = payload;
  598. if (!firstName || !lastName) throw new Error('No name data provided.');
  599. const resolvedAge = age ?? (year ? new Date().getFullYear() - Number(year) : null);
  600. const hasBirthdayData = [year, month, day].every(value => value != null && !Number.isNaN(Number(value)));
  601. if (!hasBirthdayData && (resolvedAge == null || Number.isNaN(Number(resolvedAge)))) {
  602. throw new Error('No birthday or age data provided.');
  603. }
  604. const fullName = `${firstName} ${lastName}`;
  605. log(`Step 5: Filling name: ${fullName}`);
  606. // Actual DOM structure:
  607. // - Full name: <input name="name" placeholder="全名" type="text">
  608. // - Birthday: React Aria DateField or hidden input[name="birthday"]
  609. // - Age: <input name="age" type="text|number">
  610. // --- Full Name (single field, not first+last) ---
  611. let nameInput = null;
  612. try {
  613. nameInput = await waitForElement(
  614. 'input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]',
  615. 10000
  616. );
  617. } catch {
  618. throw new Error('Could not find name input. URL: ' + location.href);
  619. }
  620. await humanPause(500, 1300);
  621. fillInput(nameInput, fullName);
  622. log(`Step 5: Name filled: ${fullName}`);
  623. // Detect birthday/age input type with polling
  624. let ageInput = null;
  625. let hasBirthdayUI = false;
  626. for (let i = 0; i < 100; i++) {
  627. ageInput = document.querySelector('input[name="age"]');
  628. // Some pages include a hidden birthday input even though the real UI is "age".
  629. // In that case we must prioritize filling age to satisfy required validation.
  630. if (ageInput) break;
  631. // Check for any supported birthday UI (spinbuttons, selects, date input, hidden)
  632. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  633. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  634. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  635. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  636. const dateInput = document.querySelector('input[type="date"]');
  637. const selects = document.querySelectorAll('select');
  638. if ((yearSpinner && monthSpinner && daySpinner) || hiddenBirthday || dateInput || selects.length >= 2) {
  639. hasBirthdayUI = true;
  640. break;
  641. }
  642. await sleep(100);
  643. }
  644. if (hasBirthdayUI) {
  645. if (!hasBirthdayData) {
  646. throw new Error('Birthday field detected, but no birthday data provided.');
  647. }
  648. // Use shared helper that tries spinbuttons → selects → date input → hidden input
  649. const filled = await fillBirthdayFields(year, month, day, 'Step 5');
  650. if (!filled) {
  651. log('Step 5: Warning - could not fill any visible birthday control', 'warn');
  652. }
  653. } else if (ageInput) {
  654. if (resolvedAge == null || Number.isNaN(Number(resolvedAge))) {
  655. throw new Error('Age field detected, but no age data provided.');
  656. }
  657. await humanPause(500, 1300);
  658. fillInput(ageInput, String(resolvedAge));
  659. log(`Step 5: Age filled: ${resolvedAge}`);
  660. // Some age-mode pages still submit a hidden birthday field.
  661. // Keep it aligned with generated data so backend validation won't reject.
  662. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  663. if (hiddenBirthday && hasBirthdayData) {
  664. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  665. hiddenBirthday.value = dateStr;
  666. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  667. log(`Step 5: Hidden birthday input set (age mode): ${dateStr}`);
  668. }
  669. } else {
  670. throw new Error('Could not find birthday or age input. URL: ' + location.href);
  671. }
  672. // Click "完成帐户创建" button
  673. await sleep(500);
  674. const completeBtn = document.querySelector('button[type="submit"]')
  675. || await waitForElementByText('button', /完成|create|continue|finish|done|agree/i, 5000).catch(() => null);
  676. // Report complete BEFORE submit (page navigates to add-phone after this)
  677. reportComplete(5);
  678. if (completeBtn) {
  679. await humanPause(500, 1300);
  680. simulateClick(completeBtn);
  681. log('Step 5: Clicked "完成帐户创建"');
  682. }
  683. }