signup-page.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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({ allowDisabled = false } = {}) {
  477. const direct = document.querySelector('button[type="submit"]');
  478. if (direct && isVisibleElement(direct) && (allowDisabled || 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) || (!allowDisabled && !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. function inspectSignupVerificationState() {
  511. if (isStep5Ready()) {
  512. return { state: 'step5' };
  513. }
  514. if (isVerificationPageStillVisible()) {
  515. return { state: 'verification' };
  516. }
  517. if (isSignupPasswordErrorPage()) {
  518. return {
  519. state: 'error',
  520. retryButton: getSignupRetryButton(),
  521. };
  522. }
  523. const passwordInput = getSignupPasswordInput();
  524. if (passwordInput) {
  525. return {
  526. state: 'password',
  527. passwordInput,
  528. submitButton: getSignupPasswordSubmitButton({ allowDisabled: true }),
  529. };
  530. }
  531. return { state: 'unknown' };
  532. }
  533. async function waitForSignupVerificationTransition(timeout = 5000) {
  534. const start = Date.now();
  535. while (Date.now() - start < timeout) {
  536. throwIfStopped();
  537. const snapshot = inspectSignupVerificationState();
  538. if (snapshot.state === 'step5' || snapshot.state === 'verification' || snapshot.state === 'error') {
  539. return snapshot;
  540. }
  541. await sleep(200);
  542. }
  543. return inspectSignupVerificationState();
  544. }
  545. async function prepareSignupVerificationFlow(payload = {}, timeout = 30000) {
  546. const { password } = payload;
  547. const start = Date.now();
  548. let recoveryRound = 0;
  549. const maxRecoveryRounds = 3;
  550. while (Date.now() - start < timeout && recoveryRound < maxRecoveryRounds) {
  551. throwIfStopped();
  552. const roundNo = recoveryRound + 1;
  553. log(`步骤 4:等待页面进入验证码阶段(第 ${roundNo}/${maxRecoveryRounds} 轮,先等待 5 秒)...`, 'info');
  554. const snapshot = await waitForSignupVerificationTransition(5000);
  555. if (snapshot.state === 'step5') {
  556. log('步骤 4:页面已进入验证码后的下一阶段,本步骤按已完成处理。', 'ok');
  557. return { ready: true, alreadyVerified: true, retried: recoveryRound };
  558. }
  559. if (snapshot.state === 'verification') {
  560. log(`步骤 4:验证码页面已就绪${recoveryRound ? `(期间自动恢复 ${recoveryRound} 次)` : ''}。`, 'ok');
  561. return { ready: true, retried: recoveryRound };
  562. }
  563. recoveryRound += 1;
  564. if (snapshot.state === 'error') {
  565. if (snapshot.retryButton && isActionEnabled(snapshot.retryButton)) {
  566. log(`步骤 4:检测到密码页超时报错,正在点击“重试”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  567. await humanPause(350, 900);
  568. simulateClick(snapshot.retryButton);
  569. await sleep(1200);
  570. continue;
  571. }
  572. log(`步骤 4:检测到异常页,但“重试”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  573. continue;
  574. }
  575. if (snapshot.state === 'password') {
  576. if (!password) {
  577. throw new Error('当前回到了密码页,但没有可用密码,无法自动重新提交。');
  578. }
  579. if ((snapshot.passwordInput.value || '') !== password) {
  580. log('步骤 4:页面仍停留在密码页,正在重新填写密码...', 'warn');
  581. await humanPause(450, 1100);
  582. fillInput(snapshot.passwordInput, password);
  583. }
  584. if (snapshot.submitButton && isActionEnabled(snapshot.submitButton)) {
  585. log(`步骤 4:页面仍停留在密码页,正在重新点击“继续”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  586. await humanPause(350, 900);
  587. simulateClick(snapshot.submitButton);
  588. await sleep(1200);
  589. continue;
  590. }
  591. log(`步骤 4:页面仍停留在密码页,但“继续”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  592. continue;
  593. }
  594. log(`步骤 4:页面仍在切换中,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  595. }
  596. throw new Error(`等待注册验证码页面就绪超时或自动恢复失败(已尝试 ${recoveryRound}/${maxRecoveryRounds} 轮)。URL: ${location.href}`);
  597. }
  598. async function waitForVerificationSubmitOutcome(step, timeout) {
  599. const resolvedTimeout = timeout ?? (step === 7 ? 30000 : 12000);
  600. const start = Date.now();
  601. while (Date.now() - start < resolvedTimeout) {
  602. throwIfStopped();
  603. const errorText = getVerificationErrorText();
  604. if (errorText) {
  605. return { invalidCode: true, errorText };
  606. }
  607. if (step === 4 && isStep5Ready()) {
  608. return { success: true };
  609. }
  610. if (step === 7 && isStep8Ready()) {
  611. return { success: true };
  612. }
  613. if (step === 7 && isAddPhonePageReady()) {
  614. return { success: true, addPhonePage: true };
  615. }
  616. await sleep(150);
  617. }
  618. if (isVerificationPageStillVisible()) {
  619. return {
  620. invalidCode: true,
  621. errorText: getVerificationErrorText() || '提交后仍停留在验证码页面,准备重新发送验证码。',
  622. };
  623. }
  624. return { success: true, assumed: true };
  625. }
  626. async function fillVerificationCode(step, payload) {
  627. const { code } = payload;
  628. if (!code) throw new Error('未提供验证码。');
  629. log(`步骤 ${step}:正在填写验证码:${code}`);
  630. if (step === 7) {
  631. await prepareLoginCodeFlow();
  632. }
  633. // Find code input — could be a single input or multiple separate inputs
  634. let codeInput = null;
  635. try {
  636. codeInput = await waitForElement(VERIFICATION_CODE_INPUT_SELECTOR, 10000);
  637. } catch {
  638. // Check for multiple single-digit inputs (common pattern)
  639. const singleInputs = document.querySelectorAll('input[maxlength="1"]');
  640. if (singleInputs.length >= 6) {
  641. log(`步骤 ${step}:发现分开的单字符验证码输入框,正在逐个填写...`);
  642. for (let i = 0; i < 6 && i < singleInputs.length; i++) {
  643. fillInput(singleInputs[i], code[i]);
  644. await sleep(100);
  645. }
  646. const outcome = await waitForVerificationSubmitOutcome(step);
  647. if (outcome.invalidCode) {
  648. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  649. } else if (outcome.addPhonePage) {
  650. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  651. } else {
  652. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  653. }
  654. return outcome;
  655. }
  656. throw new Error('未找到验证码输入框。URL: ' + location.href);
  657. }
  658. fillInput(codeInput, code);
  659. log(`步骤 ${step}:验证码已填写`);
  660. // Report complete BEFORE submit (page may navigate away)
  661. // Submit
  662. await sleep(500);
  663. const submitBtn = document.querySelector('button[type="submit"]')
  664. || await waitForElementByText('button', /verify|confirm|submit|continue|确认|验证/i, 5000).catch(() => null);
  665. if (submitBtn) {
  666. await humanPause(450, 1200);
  667. simulateClick(submitBtn);
  668. log(`步骤 ${step}:验证码已提交`);
  669. }
  670. const outcome = await waitForVerificationSubmitOutcome(step);
  671. if (outcome.invalidCode) {
  672. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  673. } else if (outcome.addPhonePage) {
  674. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  675. } else {
  676. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  677. }
  678. return outcome;
  679. }
  680. // ============================================================
  681. // Step 6: Login with registered account (on OAuth auth page)
  682. // ============================================================
  683. async function step6_login(payload) {
  684. const { email, password } = payload;
  685. if (!email) throw new Error('登录时缺少邮箱地址。');
  686. log(`步骤 6:正在使用 ${email} 登录...`);
  687. // Wait for email input on the auth page
  688. let emailInput = null;
  689. try {
  690. emailInput = await waitForElement(
  691. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email" i], input[placeholder*="Email"]',
  692. 15000
  693. );
  694. } catch {
  695. throw new Error('在登录页未找到邮箱输入框。URL: ' + location.href);
  696. }
  697. await humanPause(500, 1400);
  698. fillInput(emailInput, email);
  699. log('步骤 6:邮箱已填写');
  700. // Submit email
  701. await sleep(500);
  702. const submitBtn1 = document.querySelector('button[type="submit"]')
  703. || await waitForElementByText('button', /continue|next|submit|继续|下一步/i, 5000).catch(() => null);
  704. if (submitBtn1) {
  705. await humanPause(400, 1100);
  706. simulateClick(submitBtn1);
  707. log('步骤 6:邮箱已提交');
  708. }
  709. await sleep(2000);
  710. // Check for password field
  711. const passwordInput = document.querySelector('input[type="password"]');
  712. if (passwordInput) {
  713. log('步骤 6:已找到密码输入框,正在填写密码...');
  714. await humanPause(550, 1450);
  715. fillInput(passwordInput, password);
  716. await sleep(500);
  717. const submitBtn2 = document.querySelector('button[type="submit"]')
  718. || await waitForElementByText('button', /continue|log\s*in|submit|sign\s*in|登录|继续/i, 5000).catch(() => null);
  719. // Report complete BEFORE submit in case page navigates
  720. reportComplete(6, { needsOTP: true });
  721. if (submitBtn2) {
  722. await humanPause(450, 1200);
  723. simulateClick(submitBtn2);
  724. log('步骤 6:密码已提交,可能还需要验证码(步骤 7)');
  725. }
  726. return;
  727. }
  728. // No password field — OTP flow
  729. log('步骤 6:未发现密码输入框,可能进入验证码流程或自动跳转。');
  730. reportComplete(6, { needsOTP: true });
  731. }
  732. // ============================================================
  733. // Step 8: Find "继续" on OAuth consent page for debugger click
  734. // ============================================================
  735. // After login + verification, page shows:
  736. // "使用 ChatGPT 登录到 Codex" with a "继续" submit button.
  737. // Background performs the actual click through the debugger Input API.
  738. async function step8_findAndClick() {
  739. log('步骤 8:正在查找 OAuth 同意页的“继续”按钮...');
  740. const continueBtn = await findContinueButton();
  741. await waitForButtonEnabled(continueBtn);
  742. await humanPause(350, 900);
  743. continueBtn.scrollIntoView({ behavior: 'smooth', block: 'center' });
  744. continueBtn.focus();
  745. await sleep(250);
  746. const rect = getSerializableRect(continueBtn);
  747. log('步骤 8:已找到“继续”按钮并准备好调试器点击坐标。');
  748. return {
  749. rect,
  750. buttonText: (continueBtn.textContent || '').trim(),
  751. url: location.href,
  752. };
  753. }
  754. async function findContinueButton() {
  755. const start = Date.now();
  756. while (Date.now() - start < 10000) {
  757. throwIfStopped();
  758. if (isAddPhonePageReady()) {
  759. throw new Error('当前页面已进入手机号页面,不是 OAuth 授权同意页。URL: ' + location.href);
  760. }
  761. const button = getPrimaryContinueButton();
  762. if (button && isStep8Ready()) {
  763. return button;
  764. }
  765. await sleep(150);
  766. }
  767. throw new Error('在 OAuth 同意页未找到“继续”按钮,或页面尚未进入授权同意状态。URL: ' + location.href);
  768. }
  769. async function waitForButtonEnabled(button, timeout = 8000) {
  770. const start = Date.now();
  771. while (Date.now() - start < timeout) {
  772. throwIfStopped();
  773. if (isButtonEnabled(button)) return;
  774. await sleep(150);
  775. }
  776. throw new Error('“继续”按钮长时间不可点击。URL: ' + location.href);
  777. }
  778. function isButtonEnabled(button) {
  779. return Boolean(button)
  780. && !button.disabled
  781. && button.getAttribute('aria-disabled') !== 'true';
  782. }
  783. function getSerializableRect(el) {
  784. const rect = el.getBoundingClientRect();
  785. if (!rect.width || !rect.height) {
  786. throw new Error('滚动后“继续”按钮没有可点击尺寸。URL: ' + location.href);
  787. }
  788. return {
  789. left: rect.left,
  790. top: rect.top,
  791. width: rect.width,
  792. height: rect.height,
  793. centerX: rect.left + (rect.width / 2),
  794. centerY: rect.top + (rect.height / 2),
  795. };
  796. }
  797. // ============================================================
  798. // Step 5: Fill Name & Birthday / Age
  799. // ============================================================
  800. async function step5_fillNameBirthday(payload) {
  801. const { firstName, lastName, age, year, month, day } = payload;
  802. if (!firstName || !lastName) throw new Error('未提供姓名数据。');
  803. const resolvedAge = age ?? (year ? new Date().getFullYear() - Number(year) : null);
  804. const hasBirthdayData = [year, month, day].every(value => value != null && !Number.isNaN(Number(value)));
  805. if (!hasBirthdayData && (resolvedAge == null || Number.isNaN(Number(resolvedAge)))) {
  806. throw new Error('未提供生日或年龄数据。');
  807. }
  808. const fullName = `${firstName} ${lastName}`;
  809. log(`步骤 5:正在填写姓名:${fullName}`);
  810. // Actual DOM structure:
  811. // - Full name: <input name="name" placeholder="全名" type="text">
  812. // - Birthday: React Aria DateField or hidden input[name="birthday"]
  813. // - Age: <input name="age" type="text|number">
  814. // --- Full Name (single field, not first+last) ---
  815. let nameInput = null;
  816. try {
  817. nameInput = await waitForElement(
  818. 'input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]',
  819. 10000
  820. );
  821. } catch {
  822. throw new Error('未找到姓名输入框。URL: ' + location.href);
  823. }
  824. await humanPause(500, 1300);
  825. fillInput(nameInput, fullName);
  826. log(`步骤 5:姓名已填写:${fullName}`);
  827. let birthdayMode = false;
  828. let ageInput = null;
  829. for (let i = 0; i < 100; i++) {
  830. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  831. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  832. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  833. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  834. ageInput = document.querySelector('input[name="age"]');
  835. if ((yearSpinner && monthSpinner && daySpinner) || hiddenBirthday) {
  836. birthdayMode = true;
  837. break;
  838. }
  839. if (ageInput) break;
  840. await sleep(100);
  841. }
  842. if (birthdayMode) {
  843. if (!hasBirthdayData) {
  844. throw new Error('检测到生日字段,但未提供生日数据。');
  845. }
  846. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  847. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  848. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  849. const yearReactSelect = findBirthdayReactAriaSelect('年');
  850. const monthReactSelect = findBirthdayReactAriaSelect('月');
  851. const dayReactSelect = findBirthdayReactAriaSelect('天');
  852. if (yearReactSelect?.nativeSelect && monthReactSelect?.nativeSelect && dayReactSelect?.nativeSelect) {
  853. const desiredDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  854. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  855. log('步骤 5:检测到 React Aria 下拉生日字段,正在填写生日...');
  856. await humanPause(450, 1100);
  857. await setReactAriaBirthdaySelect(yearReactSelect, year);
  858. await humanPause(250, 650);
  859. await setReactAriaBirthdaySelect(monthReactSelect, month);
  860. await humanPause(250, 650);
  861. await setReactAriaBirthdaySelect(dayReactSelect, day);
  862. if (hiddenBirthday) {
  863. const start = Date.now();
  864. while (Date.now() - start < 2000) {
  865. if ((hiddenBirthday.value || '') === desiredDate) break;
  866. await sleep(100);
  867. }
  868. if ((hiddenBirthday.value || '') !== desiredDate) {
  869. throw new Error(`生日值未成功写入页面。期望 ${desiredDate},实际 ${(hiddenBirthday.value || '空')}。`);
  870. }
  871. }
  872. log(`步骤 5:React Aria 生日已填写:${desiredDate}`);
  873. }
  874. if (yearSpinner && monthSpinner && daySpinner) {
  875. log('步骤 5:检测到生日字段,正在填写生日...');
  876. async function setSpinButton(el, value) {
  877. el.focus();
  878. await sleep(100);
  879. document.execCommand('selectAll', false, null);
  880. await sleep(50);
  881. const valueStr = String(value);
  882. for (const char of valueStr) {
  883. el.dispatchEvent(new KeyboardEvent('keydown', { key: char, code: `Digit${char}`, bubbles: true }));
  884. el.dispatchEvent(new KeyboardEvent('keypress', { key: char, code: `Digit${char}`, bubbles: true }));
  885. el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: char, bubbles: true }));
  886. el.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: char, bubbles: true }));
  887. await sleep(50);
  888. }
  889. el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab', code: 'Tab', bubbles: true }));
  890. el.blur();
  891. await sleep(100);
  892. }
  893. await humanPause(450, 1100);
  894. await setSpinButton(yearSpinner, year);
  895. await humanPause(250, 650);
  896. await setSpinButton(monthSpinner, String(month).padStart(2, '0'));
  897. await humanPause(250, 650);
  898. await setSpinButton(daySpinner, String(day).padStart(2, '0'));
  899. log(`步骤 5:生日已填写:${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
  900. }
  901. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  902. if (hiddenBirthday) {
  903. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  904. hiddenBirthday.value = dateStr;
  905. hiddenBirthday.dispatchEvent(new Event('input', { bubbles: true }));
  906. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  907. log(`步骤 5:已设置隐藏生日输入框:${dateStr}`);
  908. }
  909. } else if (ageInput) {
  910. if (resolvedAge == null || Number.isNaN(Number(resolvedAge))) {
  911. throw new Error('检测到年龄字段,但未提供年龄数据。');
  912. }
  913. await humanPause(500, 1300);
  914. fillInput(ageInput, String(resolvedAge));
  915. log(`步骤 5:年龄已填写:${resolvedAge}`);
  916. } else {
  917. throw new Error('未找到生日或年龄输入项。URL: ' + location.href);
  918. }
  919. // Click "完成帐户创建" button
  920. await sleep(500);
  921. const completeBtn = document.querySelector('button[type="submit"]')
  922. || await waitForElementByText('button', /完成|create|continue|finish|done|agree/i, 5000).catch(() => null);
  923. if (!completeBtn) {
  924. throw new Error('未找到“完成帐户创建”按钮。URL: ' + location.href);
  925. }
  926. await humanPause(500, 1300);
  927. simulateClick(completeBtn);
  928. log('步骤 5:已点击“完成帐户创建”,正在等待页面结果...');
  929. const outcome = await waitForStep5SubmitOutcome();
  930. if (outcome.invalidProfile) {
  931. throw new Error(`步骤 5:${outcome.errorText}`);
  932. }
  933. log(`步骤 5:资料已通过。`, 'ok');
  934. reportComplete(5, { addPhonePage: Boolean(outcome.addPhonePage) });
  935. }