signup-page.js 40 KB

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