signup-page.js 47 KB

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