signup-page.js 36 KB

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