signup-page.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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 === 'RESEND_VERIFICATION_CODE'
  12. ) {
  13. resetStopState();
  14. handleCommand(message).then((result) => {
  15. sendResponse({ ok: true, ...(result || {}) });
  16. }).catch(err => {
  17. if (isStopError(err)) {
  18. log(`步骤 ${message.step || 8}:已被用户停止。`, 'warn');
  19. sendResponse({ stopped: true, error: err.message });
  20. return;
  21. }
  22. if (message.type === 'STEP8_FIND_AND_CLICK') {
  23. log(`步骤 8:${err.message}`, 'error');
  24. sendResponse({ error: err.message });
  25. return;
  26. }
  27. reportError(message.step, err.message);
  28. sendResponse({ error: err.message });
  29. });
  30. return true;
  31. }
  32. });
  33. async function handleCommand(message) {
  34. switch (message.type) {
  35. case 'EXECUTE_STEP':
  36. switch (message.step) {
  37. case 2: return await step2_clickRegister();
  38. case 3: return await step3_fillEmailPassword(message.payload);
  39. case 5: return await step5_fillNameBirthday(message.payload);
  40. case 6: return await step6_login(message.payload);
  41. case 8: return await step8_findAndClick();
  42. default: throw new Error(`signup-page.js 不处理步骤 ${message.step}`);
  43. }
  44. case 'FILL_CODE':
  45. // Step 4 = signup code, Step 7 = login code (same handler)
  46. return await fillVerificationCode(message.step, message.payload);
  47. case 'PREPARE_LOGIN_CODE':
  48. return await prepareLoginCodeFlow();
  49. case 'RESEND_VERIFICATION_CODE':
  50. return await resendVerificationCode(message.step);
  51. case 'STEP8_FIND_AND_CLICK':
  52. return await step8_findAndClick();
  53. }
  54. }
  55. const VERIFICATION_CODE_INPUT_SELECTOR = [
  56. 'input[name="code"]',
  57. 'input[name="otp"]',
  58. 'input[autocomplete="one-time-code"]',
  59. 'input[type="text"][maxlength="6"]',
  60. 'input[type="tel"][maxlength="6"]',
  61. 'input[aria-label*="code" i]',
  62. 'input[placeholder*="code" i]',
  63. 'input[inputmode="numeric"]',
  64. ].join(', ');
  65. 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;
  66. 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;
  67. function isVisibleElement(el) {
  68. if (!el) return false;
  69. const style = window.getComputedStyle(el);
  70. const rect = el.getBoundingClientRect();
  71. return style.display !== 'none'
  72. && style.visibility !== 'hidden'
  73. && rect.width > 0
  74. && rect.height > 0;
  75. }
  76. function getVerificationCodeTarget() {
  77. const codeInput = document.querySelector(VERIFICATION_CODE_INPUT_SELECTOR);
  78. if (codeInput && isVisibleElement(codeInput)) {
  79. return { type: 'single', element: codeInput };
  80. }
  81. const singleInputs = Array.from(document.querySelectorAll('input[maxlength="1"]'))
  82. .filter(isVisibleElement);
  83. if (singleInputs.length >= 6) {
  84. return { type: 'split', elements: singleInputs };
  85. }
  86. return null;
  87. }
  88. function getActionText(el) {
  89. return [
  90. el?.textContent,
  91. el?.value,
  92. el?.getAttribute?.('aria-label'),
  93. el?.getAttribute?.('title'),
  94. ]
  95. .filter(Boolean)
  96. .join(' ')
  97. .replace(/\s+/g, ' ')
  98. .trim();
  99. }
  100. function isActionEnabled(el) {
  101. return Boolean(el)
  102. && !el.disabled
  103. && el.getAttribute('aria-disabled') !== 'true';
  104. }
  105. function findOneTimeCodeLoginTrigger() {
  106. const candidates = document.querySelectorAll(
  107. 'button, a, [role="button"], [role="link"], input[type="button"], input[type="submit"]'
  108. );
  109. for (const el of candidates) {
  110. if (!isVisibleElement(el)) continue;
  111. if (el.disabled || el.getAttribute('aria-disabled') === 'true') continue;
  112. const text = [
  113. el.textContent,
  114. el.value,
  115. el.getAttribute('aria-label'),
  116. el.getAttribute('title'),
  117. ]
  118. .filter(Boolean)
  119. .join(' ')
  120. .replace(/\s+/g, ' ')
  121. .trim();
  122. if (text && ONE_TIME_CODE_LOGIN_PATTERN.test(text)) {
  123. return el;
  124. }
  125. }
  126. return null;
  127. }
  128. function findResendVerificationCodeTrigger({ allowDisabled = false } = {}) {
  129. const candidates = document.querySelectorAll(
  130. 'button, a, [role="button"], [role="link"], input[type="button"], input[type="submit"]'
  131. );
  132. for (const el of candidates) {
  133. if (!isVisibleElement(el)) continue;
  134. if (!allowDisabled && !isActionEnabled(el)) continue;
  135. const text = getActionText(el);
  136. if (text && RESEND_VERIFICATION_CODE_PATTERN.test(text)) {
  137. return el;
  138. }
  139. }
  140. return null;
  141. }
  142. async function prepareLoginCodeFlow(timeout = 15000) {
  143. const readyTarget = getVerificationCodeTarget();
  144. if (readyTarget) {
  145. log('步骤 7:验证码输入框已就绪。');
  146. return { ready: true, mode: readyTarget.type };
  147. }
  148. const start = Date.now();
  149. let switchClickCount = 0;
  150. let lastSwitchAttemptAt = 0;
  151. let loggedPasswordPage = false;
  152. while (Date.now() - start < timeout) {
  153. throwIfStopped();
  154. const target = getVerificationCodeTarget();
  155. if (target) {
  156. log('步骤 7:验证码页面已就绪。');
  157. return { ready: true, mode: target.type };
  158. }
  159. const passwordInput = document.querySelector('input[type="password"]');
  160. const switchTrigger = findOneTimeCodeLoginTrigger();
  161. if (switchTrigger && (switchClickCount === 0 || Date.now() - lastSwitchAttemptAt > 1500)) {
  162. switchClickCount += 1;
  163. lastSwitchAttemptAt = Date.now();
  164. loggedPasswordPage = false;
  165. log('步骤 7:检测到密码页,正在切换到一次性验证码登录...');
  166. await humanPause(350, 900);
  167. simulateClick(switchTrigger);
  168. await sleep(1200);
  169. continue;
  170. }
  171. if (passwordInput && !loggedPasswordPage) {
  172. loggedPasswordPage = true;
  173. log('步骤 7:正在等待密码页上的一次性验证码登录入口...');
  174. }
  175. await sleep(200);
  176. }
  177. throw new Error('无法切换到一次性验证码验证页面。URL: ' + location.href);
  178. }
  179. async function resendVerificationCode(step, timeout = 45000) {
  180. if (step === 7) {
  181. await prepareLoginCodeFlow();
  182. }
  183. const start = Date.now();
  184. let action = null;
  185. let loggedWaiting = false;
  186. while (Date.now() - start < timeout) {
  187. throwIfStopped();
  188. action = findResendVerificationCodeTrigger({ allowDisabled: true });
  189. if (action && isActionEnabled(action)) {
  190. log(`步骤 ${step}:重新发送验证码按钮已可用。`);
  191. await humanPause(350, 900);
  192. simulateClick(action);
  193. await sleep(1200);
  194. return {
  195. resent: true,
  196. buttonText: getActionText(action),
  197. };
  198. }
  199. if (action && !loggedWaiting) {
  200. loggedWaiting = true;
  201. log(`步骤 ${step}:正在等待重新发送验证码按钮变为可点击...`);
  202. }
  203. await sleep(250);
  204. }
  205. throw new Error('无法点击重新发送验证码按钮。URL: ' + location.href);
  206. }
  207. // ============================================================
  208. // Step 2: Click Register
  209. // ============================================================
  210. async function step2_clickRegister() {
  211. log('步骤 2:正在查找注册按钮...');
  212. let registerBtn = null;
  213. try {
  214. registerBtn = await waitForElementByText(
  215. 'a, button, [role="button"], [role="link"]',
  216. /sign\s*up|register|create\s*account|注册/i,
  217. 10000
  218. );
  219. } catch {
  220. // Some pages may have a direct link
  221. try {
  222. registerBtn = await waitForElement('a[href*="signup"], a[href*="register"]', 5000);
  223. } catch {
  224. throw new Error(
  225. '未找到注册按钮。' +
  226. '请在 DevTools 中检查认证页面 DOM。URL: ' + location.href
  227. );
  228. }
  229. }
  230. await humanPause(450, 1200);
  231. reportComplete(2);
  232. simulateClick(registerBtn);
  233. log('步骤 2:已点击注册按钮');
  234. }
  235. // ============================================================
  236. // Step 3: Fill Email & Password
  237. // ============================================================
  238. async function step3_fillEmailPassword(payload) {
  239. const { email } = payload;
  240. if (!email) throw new Error('未提供邮箱地址,请先在侧边栏粘贴邮箱。');
  241. log(`步骤 3:正在填写邮箱:${email}`);
  242. // Find email input
  243. let emailInput = null;
  244. try {
  245. emailInput = await waitForElement(
  246. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email"], input[placeholder*="Email"]',
  247. 10000
  248. );
  249. } catch {
  250. throw new Error('在注册页未找到邮箱输入框。URL: ' + location.href);
  251. }
  252. await humanPause(500, 1400);
  253. fillInput(emailInput, email);
  254. log('步骤 3:邮箱已填写');
  255. // Check if password field is on the same page
  256. let passwordInput = document.querySelector('input[type="password"]');
  257. if (!passwordInput) {
  258. // Need to submit email first to get to password page
  259. log('步骤 3:暂未发现密码输入框,先提交邮箱...');
  260. const submitBtn = document.querySelector('button[type="submit"]')
  261. || await waitForElementByText('button', /continue|next|submit|继续|下一步/i, 5000).catch(() => null);
  262. if (submitBtn) {
  263. await humanPause(400, 1100);
  264. simulateClick(submitBtn);
  265. log('步骤 3:邮箱已提交,正在等待密码输入框...');
  266. await sleep(2000);
  267. }
  268. try {
  269. passwordInput = await waitForElement('input[type="password"]', 10000);
  270. } catch {
  271. throw new Error('提交邮箱后仍未找到密码输入框。URL: ' + location.href);
  272. }
  273. }
  274. if (!payload.password) throw new Error('未提供密码,步骤 3 需要可用密码。');
  275. await humanPause(600, 1500);
  276. fillInput(passwordInput, payload.password);
  277. log('步骤 3:密码已填写');
  278. // Report complete BEFORE submit, because submit causes page navigation
  279. // which kills the content script connection
  280. reportComplete(3, { email });
  281. // Submit the form (page will navigate away after this)
  282. await sleep(500);
  283. const submitBtn = document.querySelector('button[type="submit"]')
  284. || await waitForElementByText('button', /continue|sign\s*up|submit|注册|创建|create/i, 5000).catch(() => null);
  285. if (submitBtn) {
  286. await humanPause(500, 1300);
  287. simulateClick(submitBtn);
  288. log('步骤 3:表单已提交');
  289. }
  290. }
  291. // ============================================================
  292. // Fill Verification Code (used by step 4 and step 7)
  293. // ============================================================
  294. const INVALID_VERIFICATION_CODE_PATTERN = /代码不正确|验证码不正确|验证码错误|code\s+(?:is\s+)?incorrect|invalid\s+code|incorrect\s+code|try\s+again/i;
  295. const VERIFICATION_PAGE_PATTERN = /检查您的收件箱|输入我们刚刚向|重新发送电子邮件|重新发送验证码|验证码|代码不正确|email\s+verification/i;
  296. const OAUTH_CONSENT_PAGE_PATTERN = /使用\s*ChatGPT\s*登录到\s*Codex|login\s+to\s+codex|log\s+in\s+to\s+codex|authorize|授权/i;
  297. const ADD_PHONE_PAGE_PATTERN = /add[\s-]*phone|添加手机号|手机号码|手机号|phone\s+number|telephone/i;
  298. function getVerificationErrorText() {
  299. const messages = [];
  300. const selectors = [
  301. '.react-aria-FieldError',
  302. '[slot="errorMessage"]',
  303. '[id$="-error"]',
  304. '[data-invalid="true"] + *',
  305. '[aria-invalid="true"] + *',
  306. '[class*="error"]',
  307. ];
  308. for (const selector of selectors) {
  309. document.querySelectorAll(selector).forEach((el) => {
  310. const text = (el.textContent || '').replace(/\s+/g, ' ').trim();
  311. if (text) {
  312. messages.push(text);
  313. }
  314. });
  315. }
  316. const invalidInput = document.querySelector(`${VERIFICATION_CODE_INPUT_SELECTOR}[aria-invalid="true"], ${VERIFICATION_CODE_INPUT_SELECTOR}[data-invalid="true"]`);
  317. if (invalidInput) {
  318. const wrapper = invalidInput.closest('form, [data-rac], ._root_18qcl_51, div');
  319. if (wrapper) {
  320. const text = (wrapper.textContent || '').replace(/\s+/g, ' ').trim();
  321. if (text) {
  322. messages.push(text);
  323. }
  324. }
  325. }
  326. return messages.find((text) => INVALID_VERIFICATION_CODE_PATTERN.test(text)) || '';
  327. }
  328. function isStep5Ready() {
  329. return Boolean(
  330. document.querySelector('input[name="name"], input[autocomplete="name"], input[name="birthday"], input[name="age"], [role="spinbutton"][data-type="year"]')
  331. );
  332. }
  333. function getPageTextSnapshot() {
  334. return (document.body?.innerText || document.body?.textContent || '')
  335. .replace(/\s+/g, ' ')
  336. .trim();
  337. }
  338. function getPrimaryContinueButton() {
  339. const continueBtn = document.querySelector(
  340. 'button[type="submit"][data-dd-action-name="Continue"], button[type="submit"]._primary_3rdp0_107'
  341. );
  342. if (continueBtn && isVisibleElement(continueBtn)) {
  343. return continueBtn;
  344. }
  345. const buttons = document.querySelectorAll('button, [role="button"]');
  346. return Array.from(buttons).find((el) => isVisibleElement(el) && /继续|Continue/i.test(el.textContent || '')) || null;
  347. }
  348. function isVerificationPageStillVisible() {
  349. if (getVerificationCodeTarget()) return true;
  350. if (findResendVerificationCodeTrigger({ allowDisabled: true })) return true;
  351. if (document.querySelector('form[action*="email-verification" i]')) return true;
  352. return VERIFICATION_PAGE_PATTERN.test(getPageTextSnapshot());
  353. }
  354. function isAddPhonePageReady() {
  355. const path = `${location.pathname || ''} ${location.href || ''}`;
  356. if (/\/add-phone(?:[/?#]|$)/i.test(path)) return true;
  357. const phoneInput = document.querySelector(
  358. 'input[type="tel"]:not([maxlength="6"]), input[name*="phone" i], input[id*="phone" i], input[autocomplete="tel"]'
  359. );
  360. if (phoneInput && isVisibleElement(phoneInput)) {
  361. return true;
  362. }
  363. return ADD_PHONE_PAGE_PATTERN.test(getPageTextSnapshot());
  364. }
  365. function isStep8Ready() {
  366. const continueBtn = getPrimaryContinueButton();
  367. if (!continueBtn) return false;
  368. if (isVerificationPageStillVisible()) return false;
  369. if (isAddPhonePageReady()) return false;
  370. return OAUTH_CONSENT_PAGE_PATTERN.test(getPageTextSnapshot());
  371. }
  372. async function waitForVerificationSubmitOutcome(step, timeout) {
  373. const resolvedTimeout = timeout ?? (step === 7 ? 30000 : 12000);
  374. const start = Date.now();
  375. while (Date.now() - start < resolvedTimeout) {
  376. throwIfStopped();
  377. const errorText = getVerificationErrorText();
  378. if (errorText) {
  379. return { invalidCode: true, errorText };
  380. }
  381. if (step === 4 && isStep5Ready()) {
  382. return { success: true };
  383. }
  384. if (step === 7 && isStep8Ready()) {
  385. return { success: true };
  386. }
  387. if (step === 7 && isAddPhonePageReady()) {
  388. return { success: true, addPhonePage: true };
  389. }
  390. await sleep(150);
  391. }
  392. if (isVerificationPageStillVisible()) {
  393. return {
  394. invalidCode: true,
  395. errorText: getVerificationErrorText() || '提交后仍停留在验证码页面,准备重新发送验证码。',
  396. };
  397. }
  398. return { success: true, assumed: true };
  399. }
  400. async function fillVerificationCode(step, payload) {
  401. const { code } = payload;
  402. if (!code) throw new Error('未提供验证码。');
  403. log(`步骤 ${step}:正在填写验证码:${code}`);
  404. if (step === 7) {
  405. await prepareLoginCodeFlow();
  406. }
  407. // Find code input — could be a single input or multiple separate inputs
  408. let codeInput = null;
  409. try {
  410. codeInput = await waitForElement(VERIFICATION_CODE_INPUT_SELECTOR, 10000);
  411. } catch {
  412. // Check for multiple single-digit inputs (common pattern)
  413. const singleInputs = document.querySelectorAll('input[maxlength="1"]');
  414. if (singleInputs.length >= 6) {
  415. log(`步骤 ${step}:发现分开的单字符验证码输入框,正在逐个填写...`);
  416. for (let i = 0; i < 6 && i < singleInputs.length; i++) {
  417. fillInput(singleInputs[i], code[i]);
  418. await sleep(100);
  419. }
  420. const outcome = await waitForVerificationSubmitOutcome(step);
  421. if (outcome.invalidCode) {
  422. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  423. } else if (outcome.addPhonePage) {
  424. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  425. } else {
  426. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  427. }
  428. return outcome;
  429. }
  430. throw new Error('未找到验证码输入框。URL: ' + location.href);
  431. }
  432. fillInput(codeInput, code);
  433. log(`步骤 ${step}:验证码已填写`);
  434. // Report complete BEFORE submit (page may navigate away)
  435. // Submit
  436. await sleep(500);
  437. const submitBtn = document.querySelector('button[type="submit"]')
  438. || await waitForElementByText('button', /verify|confirm|submit|continue|确认|验证/i, 5000).catch(() => null);
  439. if (submitBtn) {
  440. await humanPause(450, 1200);
  441. simulateClick(submitBtn);
  442. log(`步骤 ${step}:验证码已提交`);
  443. }
  444. const outcome = await waitForVerificationSubmitOutcome(step);
  445. if (outcome.invalidCode) {
  446. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  447. } else if (outcome.addPhonePage) {
  448. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  449. } else {
  450. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  451. }
  452. return outcome;
  453. }
  454. // ============================================================
  455. // Step 6: Login with registered account (on OAuth auth page)
  456. // ============================================================
  457. async function step6_login(payload) {
  458. const { email, password } = payload;
  459. if (!email) throw new Error('登录时缺少邮箱地址。');
  460. log(`步骤 6:正在使用 ${email} 登录...`);
  461. // Wait for email input on the auth page
  462. let emailInput = null;
  463. try {
  464. emailInput = await waitForElement(
  465. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email" i], input[placeholder*="Email"]',
  466. 15000
  467. );
  468. } catch {
  469. throw new Error('在登录页未找到邮箱输入框。URL: ' + location.href);
  470. }
  471. await humanPause(500, 1400);
  472. fillInput(emailInput, email);
  473. log('步骤 6:邮箱已填写');
  474. // Submit email
  475. await sleep(500);
  476. const submitBtn1 = document.querySelector('button[type="submit"]')
  477. || await waitForElementByText('button', /continue|next|submit|继续|下一步/i, 5000).catch(() => null);
  478. if (submitBtn1) {
  479. await humanPause(400, 1100);
  480. simulateClick(submitBtn1);
  481. log('步骤 6:邮箱已提交');
  482. }
  483. await sleep(2000);
  484. // Check for password field
  485. const passwordInput = document.querySelector('input[type="password"]');
  486. if (passwordInput) {
  487. log('步骤 6:已找到密码输入框,正在填写密码...');
  488. await humanPause(550, 1450);
  489. fillInput(passwordInput, password);
  490. await sleep(500);
  491. const submitBtn2 = document.querySelector('button[type="submit"]')
  492. || await waitForElementByText('button', /continue|log\s*in|submit|sign\s*in|登录|继续/i, 5000).catch(() => null);
  493. // Report complete BEFORE submit in case page navigates
  494. reportComplete(6, { needsOTP: true });
  495. if (submitBtn2) {
  496. await humanPause(450, 1200);
  497. simulateClick(submitBtn2);
  498. log('步骤 6:密码已提交,可能还需要验证码(步骤 7)');
  499. }
  500. return;
  501. }
  502. // No password field — OTP flow
  503. log('步骤 6:未发现密码输入框,可能进入验证码流程或自动跳转。');
  504. reportComplete(6, { needsOTP: true });
  505. }
  506. // ============================================================
  507. // Step 8: Find "继续" on OAuth consent page for debugger click
  508. // ============================================================
  509. // After login + verification, page shows:
  510. // "使用 ChatGPT 登录到 Codex" with a "继续" submit button.
  511. // Background performs the actual click through the debugger Input API.
  512. async function step8_findAndClick() {
  513. log('步骤 8:正在查找 OAuth 同意页的“继续”按钮...');
  514. const continueBtn = await findContinueButton();
  515. await waitForButtonEnabled(continueBtn);
  516. await humanPause(350, 900);
  517. continueBtn.scrollIntoView({ behavior: 'smooth', block: 'center' });
  518. continueBtn.focus();
  519. await sleep(250);
  520. const rect = getSerializableRect(continueBtn);
  521. log('步骤 8:已找到“继续”按钮并准备好调试器点击坐标。');
  522. return {
  523. rect,
  524. buttonText: (continueBtn.textContent || '').trim(),
  525. url: location.href,
  526. };
  527. }
  528. async function findContinueButton() {
  529. const start = Date.now();
  530. while (Date.now() - start < 10000) {
  531. throwIfStopped();
  532. if (isAddPhonePageReady()) {
  533. throw new Error('当前页面已进入手机号页面,不是 OAuth 授权同意页。URL: ' + location.href);
  534. }
  535. const button = getPrimaryContinueButton();
  536. if (button && isStep8Ready()) {
  537. return button;
  538. }
  539. await sleep(150);
  540. }
  541. throw new Error('在 OAuth 同意页未找到“继续”按钮,或页面尚未进入授权同意状态。URL: ' + location.href);
  542. }
  543. async function waitForButtonEnabled(button, timeout = 8000) {
  544. const start = Date.now();
  545. while (Date.now() - start < timeout) {
  546. throwIfStopped();
  547. if (isButtonEnabled(button)) return;
  548. await sleep(150);
  549. }
  550. throw new Error('“继续”按钮长时间不可点击。URL: ' + location.href);
  551. }
  552. function isButtonEnabled(button) {
  553. return Boolean(button)
  554. && !button.disabled
  555. && button.getAttribute('aria-disabled') !== 'true';
  556. }
  557. function getSerializableRect(el) {
  558. const rect = el.getBoundingClientRect();
  559. if (!rect.width || !rect.height) {
  560. throw new Error('滚动后“继续”按钮没有可点击尺寸。URL: ' + location.href);
  561. }
  562. return {
  563. left: rect.left,
  564. top: rect.top,
  565. width: rect.width,
  566. height: rect.height,
  567. centerX: rect.left + (rect.width / 2),
  568. centerY: rect.top + (rect.height / 2),
  569. };
  570. }
  571. // ============================================================
  572. // Step 5: Fill Name & Birthday / Age
  573. // ============================================================
  574. async function step5_fillNameBirthday(payload) {
  575. const { firstName, lastName, age, year, month, day } = payload;
  576. if (!firstName || !lastName) throw new Error('未提供姓名数据。');
  577. const resolvedAge = age ?? (year ? new Date().getFullYear() - Number(year) : null);
  578. const hasBirthdayData = [year, month, day].every(value => value != null && !Number.isNaN(Number(value)));
  579. if (!hasBirthdayData && (resolvedAge == null || Number.isNaN(Number(resolvedAge)))) {
  580. throw new Error('未提供生日或年龄数据。');
  581. }
  582. const fullName = `${firstName} ${lastName}`;
  583. log(`步骤 5:正在填写姓名:${fullName}`);
  584. // Actual DOM structure:
  585. // - Full name: <input name="name" placeholder="全名" type="text">
  586. // - Birthday: React Aria DateField or hidden input[name="birthday"]
  587. // - Age: <input name="age" type="text|number">
  588. // --- Full Name (single field, not first+last) ---
  589. let nameInput = null;
  590. try {
  591. nameInput = await waitForElement(
  592. 'input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]',
  593. 10000
  594. );
  595. } catch {
  596. throw new Error('未找到姓名输入框。URL: ' + location.href);
  597. }
  598. await humanPause(500, 1300);
  599. fillInput(nameInput, fullName);
  600. log(`步骤 5:姓名已填写:${fullName}`);
  601. let birthdayMode = false;
  602. let ageInput = null;
  603. for (let i = 0; i < 100; i++) {
  604. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  605. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  606. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  607. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  608. ageInput = document.querySelector('input[name="age"]');
  609. if ((yearSpinner && monthSpinner && daySpinner) || hiddenBirthday) {
  610. birthdayMode = true;
  611. break;
  612. }
  613. if (ageInput) break;
  614. await sleep(100);
  615. }
  616. if (birthdayMode) {
  617. if (!hasBirthdayData) {
  618. throw new Error('检测到生日字段,但未提供生日数据。');
  619. }
  620. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  621. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  622. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  623. if (yearSpinner && monthSpinner && daySpinner) {
  624. log('步骤 5:检测到生日字段,正在填写生日...');
  625. async function setSpinButton(el, value) {
  626. el.focus();
  627. await sleep(100);
  628. document.execCommand('selectAll', false, null);
  629. await sleep(50);
  630. const valueStr = String(value);
  631. for (const char of valueStr) {
  632. el.dispatchEvent(new KeyboardEvent('keydown', { key: char, code: `Digit${char}`, bubbles: true }));
  633. el.dispatchEvent(new KeyboardEvent('keypress', { key: char, code: `Digit${char}`, bubbles: true }));
  634. el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: char, bubbles: true }));
  635. el.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: char, bubbles: true }));
  636. await sleep(50);
  637. }
  638. el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab', code: 'Tab', bubbles: true }));
  639. el.blur();
  640. await sleep(100);
  641. }
  642. await humanPause(450, 1100);
  643. await setSpinButton(yearSpinner, year);
  644. await humanPause(250, 650);
  645. await setSpinButton(monthSpinner, String(month).padStart(2, '0'));
  646. await humanPause(250, 650);
  647. await setSpinButton(daySpinner, String(day).padStart(2, '0'));
  648. log(`步骤 5:生日已填写:${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
  649. }
  650. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  651. if (hiddenBirthday) {
  652. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  653. hiddenBirthday.value = dateStr;
  654. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  655. log(`步骤 5:已设置隐藏生日输入框:${dateStr}`);
  656. }
  657. } else if (ageInput) {
  658. if (resolvedAge == null || Number.isNaN(Number(resolvedAge))) {
  659. throw new Error('检测到年龄字段,但未提供年龄数据。');
  660. }
  661. await humanPause(500, 1300);
  662. fillInput(ageInput, String(resolvedAge));
  663. log(`步骤 5:年龄已填写:${resolvedAge}`);
  664. } else {
  665. throw new Error('未找到生日或年龄输入项。URL: ' + location.href);
  666. }
  667. // Click "完成帐户创建" button
  668. await sleep(500);
  669. const completeBtn = document.querySelector('button[type="submit"]')
  670. || await waitForElementByText('button', /完成|create|continue|finish|done|agree/i, 5000).catch(() => null);
  671. // Report complete BEFORE submit (page navigates to add-phone after this)
  672. reportComplete(5);
  673. if (completeBtn) {
  674. await humanPause(500, 1300);
  675. simulateClick(completeBtn);
  676. log('步骤 5:已点击“完成帐户创建”');
  677. }
  678. }