signup-page.js 41 KB

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