signup-page.js 47 KB

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