signup-page.js 29 KB

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