signup-page.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 (message.type === 'EXECUTE_STEP' || message.type === 'FILL_CODE' || message.type === 'STEP8_FIND_AND_CLICK') {
  7. resetStopState();
  8. handleCommand(message).then((result) => {
  9. sendResponse({ ok: true, ...(result || {}) });
  10. }).catch(err => {
  11. if (isStopError(err)) {
  12. log(`Step ${message.step || 8}: Stopped by user.`, 'warn');
  13. sendResponse({ stopped: true, error: err.message });
  14. return;
  15. }
  16. if (message.type === 'STEP8_FIND_AND_CLICK') {
  17. log(`Step 8: ${err.message}`, 'error');
  18. sendResponse({ error: err.message });
  19. return;
  20. }
  21. reportError(message.step, err.message);
  22. sendResponse({ error: err.message });
  23. });
  24. return true;
  25. }
  26. });
  27. async function handleCommand(message) {
  28. switch (message.type) {
  29. case 'EXECUTE_STEP':
  30. switch (message.step) {
  31. case 2: return await step2_clickRegister();
  32. case 3: return await step3_fillEmailPassword(message.payload);
  33. case 5: return await step5_fillNameBirthday(message.payload);
  34. case 6: return await step6_login(message.payload);
  35. case 8: return await step8_findAndClick();
  36. default: throw new Error(`signup-page.js does not handle step ${message.step}`);
  37. }
  38. case 'FILL_CODE':
  39. // Step 4 = signup code, Step 7 = login code (same handler)
  40. return await fillVerificationCode(message.step, message.payload);
  41. case 'STEP8_FIND_AND_CLICK':
  42. return await step8_findAndClick();
  43. }
  44. }
  45. // ============================================================
  46. // Step 2: Click Register
  47. // ============================================================
  48. async function step2_clickRegister() {
  49. log('Step 2: Looking for Register/Sign up button...');
  50. let registerBtn = null;
  51. try {
  52. registerBtn = await waitForElementByText(
  53. 'a, button, [role="button"], [role="link"]',
  54. /sign\s*up|register|create\s*account|注册/i,
  55. 10000
  56. );
  57. } catch {
  58. // Some pages may have a direct link
  59. try {
  60. registerBtn = await waitForElement('a[href*="signup"], a[href*="register"]', 5000);
  61. } catch {
  62. throw new Error(
  63. 'Could not find Register/Sign up button. ' +
  64. 'Check auth page DOM in DevTools. URL: ' + location.href
  65. );
  66. }
  67. }
  68. await humanPause(450, 1200);
  69. reportComplete(2);
  70. simulateClick(registerBtn);
  71. log('Step 2: Clicked Register button');
  72. }
  73. // ============================================================
  74. // Step 3: Fill Email & Password
  75. // ============================================================
  76. async function step3_fillEmailPassword(payload) {
  77. const { email } = payload;
  78. if (!email) throw new Error('No email provided. Paste email in Side Panel first.');
  79. log(`Step 3: Filling email: ${email}`);
  80. // Find email input
  81. let emailInput = null;
  82. try {
  83. emailInput = await waitForElement(
  84. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email"], input[placeholder*="Email"]',
  85. 10000
  86. );
  87. } catch {
  88. throw new Error('Could not find email input field on signup page. URL: ' + location.href);
  89. }
  90. await humanPause(500, 1400);
  91. fillInput(emailInput, email);
  92. log('Step 3: Email filled');
  93. // Check if password field is on the same page
  94. let passwordInput = document.querySelector('input[type="password"]');
  95. if (!passwordInput) {
  96. // Need to submit email first to get to password page
  97. log('Step 3: No password field yet, submitting email first...');
  98. const submitBtn = document.querySelector('button[type="submit"]')
  99. || await waitForElementByText('button', /continue|next|submit|继续|下一步/i, 5000).catch(() => null);
  100. if (submitBtn) {
  101. await humanPause(400, 1100);
  102. simulateClick(submitBtn);
  103. log('Step 3: Submitted email, waiting for password field...');
  104. await sleep(2000);
  105. }
  106. try {
  107. passwordInput = await waitForElement('input[type="password"]', 10000);
  108. } catch {
  109. throw new Error('Could not find password input after submitting email. URL: ' + location.href);
  110. }
  111. }
  112. if (!payload.password) throw new Error('No password provided. Step 3 requires a generated password.');
  113. await humanPause(600, 1500);
  114. fillInput(passwordInput, payload.password);
  115. log('Step 3: Password filled');
  116. // Report complete BEFORE submit, because submit causes page navigation
  117. // which kills the content script connection
  118. reportComplete(3, { email });
  119. // Submit the form (page will navigate away after this)
  120. await sleep(500);
  121. const submitBtn = document.querySelector('button[type="submit"]')
  122. || await waitForElementByText('button', /continue|sign\s*up|submit|注册|创建|create/i, 5000).catch(() => null);
  123. if (submitBtn) {
  124. await humanPause(500, 1300);
  125. simulateClick(submitBtn);
  126. log('Step 3: Form submitted');
  127. }
  128. }
  129. // ============================================================
  130. // Fill Verification Code (used by step 4 and step 7)
  131. // ============================================================
  132. async function fillVerificationCode(step, payload) {
  133. const { code } = payload;
  134. if (!code) throw new Error('No verification code provided.');
  135. log(`Step ${step}: Filling verification code: ${code}`);
  136. // Find code input — could be a single input or multiple separate inputs
  137. let codeInput = null;
  138. try {
  139. codeInput = await waitForElement(
  140. 'input[name="code"], input[name="otp"], input[type="text"][maxlength="6"], input[aria-label*="code"], input[placeholder*="code"], input[placeholder*="Code"], input[inputmode="numeric"]',
  141. 10000
  142. );
  143. } catch {
  144. // Check for multiple single-digit inputs (common pattern)
  145. const singleInputs = document.querySelectorAll('input[maxlength="1"]');
  146. if (singleInputs.length >= 6) {
  147. log(`Step ${step}: Found single-digit code inputs, filling individually...`);
  148. for (let i = 0; i < 6 && i < singleInputs.length; i++) {
  149. fillInput(singleInputs[i], code[i]);
  150. await sleep(100);
  151. }
  152. await sleep(1000);
  153. reportComplete(step);
  154. return;
  155. }
  156. throw new Error('Could not find verification code input. URL: ' + location.href);
  157. }
  158. fillInput(codeInput, code);
  159. log(`Step ${step}: Code filled`);
  160. // Report complete BEFORE submit (page may navigate away)
  161. reportComplete(step);
  162. // Submit
  163. await sleep(500);
  164. const submitBtn = document.querySelector('button[type="submit"]')
  165. || await waitForElementByText('button', /verify|confirm|submit|continue|确认|验证/i, 5000).catch(() => null);
  166. if (submitBtn) {
  167. await humanPause(450, 1200);
  168. simulateClick(submitBtn);
  169. log(`Step ${step}: Verification submitted`);
  170. }
  171. }
  172. // ============================================================
  173. // Step 6: Login with registered account (on OAuth auth page)
  174. // ============================================================
  175. async function step6_login(payload) {
  176. const { email, password } = payload;
  177. if (!email) throw new Error('No email provided for login.');
  178. log(`Step 6: Logging in with ${email}...`);
  179. // Wait for email input on the auth page
  180. let emailInput = null;
  181. try {
  182. emailInput = await waitForElement(
  183. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email" i], input[placeholder*="Email"]',
  184. 15000
  185. );
  186. } catch {
  187. throw new Error('Could not find email input on login page. URL: ' + location.href);
  188. }
  189. await humanPause(500, 1400);
  190. fillInput(emailInput, email);
  191. log('Step 6: Email filled');
  192. // Submit email
  193. await sleep(500);
  194. const submitBtn1 = document.querySelector('button[type="submit"]')
  195. || await waitForElementByText('button', /continue|next|submit|继续|下一步/i, 5000).catch(() => null);
  196. if (submitBtn1) {
  197. await humanPause(400, 1100);
  198. simulateClick(submitBtn1);
  199. log('Step 6: Submitted email');
  200. }
  201. const passwordInput = await waitForLoginPasswordField();
  202. if (passwordInput) {
  203. log('Step 6: Password field found, filling password...');
  204. await humanPause(550, 1450);
  205. fillInput(passwordInput, password);
  206. await sleep(500);
  207. const submitBtn2 = document.querySelector('button[type="submit"]')
  208. || await waitForElementByText('button', /continue|log\s*in|submit|sign\s*in|登录|继续/i, 5000).catch(() => null);
  209. // Report complete BEFORE submit in case page navigates
  210. reportComplete(6, { needsOTP: true });
  211. if (submitBtn2) {
  212. await humanPause(450, 1200);
  213. simulateClick(submitBtn2);
  214. log('Step 6: Submitted password, may need verification code (step 7)');
  215. }
  216. return;
  217. }
  218. // No password field — OTP flow
  219. log('Step 6: No password field. OTP flow or auto-redirect.');
  220. reportComplete(6, { needsOTP: true });
  221. }
  222. async function waitForLoginPasswordField(timeout = 15000) {
  223. const start = Date.now();
  224. while (Date.now() - start < timeout) {
  225. throwIfStopped();
  226. const passwordInput = document.querySelector('input[type="password"]');
  227. if (passwordInput) {
  228. return passwordInput;
  229. }
  230. // Some flows skip the password screen and go straight to OTP or consent.
  231. const otpInput = document.querySelector(
  232. 'input[name="code"], input[name="otp"], input[type="text"][maxlength="6"], input[inputmode="numeric"], input[maxlength="1"]'
  233. );
  234. if (otpInput) {
  235. log('Step 6: Verification code input appeared before password field.');
  236. return null;
  237. }
  238. const consentButton = document.querySelector(
  239. 'button[type="submit"][data-dd-action-name="Continue"], button[type="submit"]._primary_3rdp0_107'
  240. );
  241. if (consentButton) {
  242. log('Step 6: Consent page appeared before password field.');
  243. return null;
  244. }
  245. await sleep(250);
  246. }
  247. log(`Step 6: Password field did not appear within ${Math.round(timeout / 1000)}s.`, 'warn');
  248. return null;
  249. }
  250. // ============================================================
  251. // Step 8: Find "继续" on OAuth consent page for debugger click
  252. // ============================================================
  253. // After login + verification, page shows:
  254. // "使用 ChatGPT 登录到 Codex" with a "继续" submit button.
  255. // Background performs the actual click through the debugger Input API.
  256. async function step8_findAndClick() {
  257. log('Step 8: Looking for OAuth consent "继续" button...');
  258. const continueBtn = await findContinueButton();
  259. await waitForButtonEnabled(continueBtn);
  260. await humanPause(350, 900);
  261. continueBtn.scrollIntoView({ behavior: 'smooth', block: 'center' });
  262. continueBtn.focus();
  263. await sleep(250);
  264. const rect = getSerializableRect(continueBtn);
  265. log('Step 8: Found "继续" button and prepared debugger click coordinates.');
  266. return {
  267. rect,
  268. buttonText: (continueBtn.textContent || '').trim(),
  269. url: location.href,
  270. };
  271. }
  272. async function findContinueButton() {
  273. try {
  274. return await waitForElement(
  275. 'button[type="submit"][data-dd-action-name="Continue"], button[type="submit"]._primary_3rdp0_107',
  276. 10000
  277. );
  278. } catch {
  279. try {
  280. return await waitForElementByText('button', /继续|Continue/, 5000);
  281. } catch {
  282. throw new Error('Could not find "继续" button on OAuth consent page. URL: ' + location.href);
  283. }
  284. }
  285. }
  286. async function waitForButtonEnabled(button, timeout = 8000) {
  287. const start = Date.now();
  288. while (Date.now() - start < timeout) {
  289. throwIfStopped();
  290. if (isButtonEnabled(button)) return;
  291. await sleep(150);
  292. }
  293. throw new Error('"继续" button stayed disabled for too long. URL: ' + location.href);
  294. }
  295. function isButtonEnabled(button) {
  296. return Boolean(button)
  297. && !button.disabled
  298. && button.getAttribute('aria-disabled') !== 'true';
  299. }
  300. function getSerializableRect(el) {
  301. const rect = el.getBoundingClientRect();
  302. if (!rect.width || !rect.height) {
  303. throw new Error('"继续" button has no clickable size after scrolling. URL: ' + location.href);
  304. }
  305. return {
  306. left: rect.left,
  307. top: rect.top,
  308. width: rect.width,
  309. height: rect.height,
  310. centerX: rect.left + (rect.width / 2),
  311. centerY: rect.top + (rect.height / 2),
  312. };
  313. }
  314. // ============================================================
  315. // Step 5: Fill Name & Birthday / Age
  316. // ============================================================
  317. async function step5_fillNameBirthday(payload) {
  318. const { firstName, lastName, age, year, month, day } = payload;
  319. if (!firstName || !lastName) throw new Error('No name data provided.');
  320. const resolvedAge = age ?? (year ? new Date().getFullYear() - Number(year) : null);
  321. const hasBirthdayData = [year, month, day].every(value => value != null && !Number.isNaN(Number(value)));
  322. if (!hasBirthdayData && (resolvedAge == null || Number.isNaN(Number(resolvedAge)))) {
  323. throw new Error('No birthday or age data provided.');
  324. }
  325. const fullName = `${firstName} ${lastName}`;
  326. log(`Step 5: Filling name: ${fullName}`);
  327. // Actual DOM structure:
  328. // - Full name: <input name="name" placeholder="全名" type="text">
  329. // - Birthday: React Aria DateField or hidden input[name="birthday"]
  330. // - Age: <input name="age" type="text|number">
  331. // --- Full Name (single field, not first+last) ---
  332. let nameInput = null;
  333. try {
  334. nameInput = await waitForElement(
  335. 'input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]',
  336. 10000
  337. );
  338. } catch {
  339. throw new Error('Could not find name input. URL: ' + location.href);
  340. }
  341. await humanPause(500, 1300);
  342. fillInput(nameInput, fullName);
  343. log(`Step 5: Name filled: ${fullName}`);
  344. let birthdayMode = false;
  345. let ageInput = null;
  346. for (let i = 0; i < 100; i++) {
  347. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  348. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  349. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  350. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  351. ageInput = document.querySelector('input[name="age"]');
  352. // Some pages include a hidden birthday input even though the real UI is "age".
  353. // In that case we must prioritize filling age to satisfy required validation.
  354. if (ageInput) break;
  355. if ((yearSpinner && monthSpinner && daySpinner) || hiddenBirthday) {
  356. birthdayMode = true;
  357. break;
  358. }
  359. await sleep(100);
  360. }
  361. if (birthdayMode) {
  362. if (!hasBirthdayData) {
  363. throw new Error('Birthday field detected, but no birthday data provided.');
  364. }
  365. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  366. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  367. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  368. if (yearSpinner && monthSpinner && daySpinner) {
  369. log('Step 5: Birthday fields detected, filling birthday...');
  370. async function setSpinButton(el, value) {
  371. el.focus();
  372. await sleep(100);
  373. document.execCommand('selectAll', false, null);
  374. await sleep(50);
  375. const valueStr = String(value);
  376. for (const char of valueStr) {
  377. el.dispatchEvent(new KeyboardEvent('keydown', { key: char, code: `Digit${char}`, bubbles: true }));
  378. el.dispatchEvent(new KeyboardEvent('keypress', { key: char, code: `Digit${char}`, bubbles: true }));
  379. el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: char, bubbles: true }));
  380. el.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: char, bubbles: true }));
  381. await sleep(50);
  382. }
  383. el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab', code: 'Tab', bubbles: true }));
  384. el.blur();
  385. await sleep(100);
  386. }
  387. await humanPause(450, 1100);
  388. await setSpinButton(yearSpinner, year);
  389. await humanPause(250, 650);
  390. await setSpinButton(monthSpinner, String(month).padStart(2, '0'));
  391. await humanPause(250, 650);
  392. await setSpinButton(daySpinner, String(day).padStart(2, '0'));
  393. log(`Step 5: Birthday filled: ${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
  394. }
  395. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  396. if (hiddenBirthday) {
  397. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  398. hiddenBirthday.value = dateStr;
  399. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  400. log(`Step 5: Hidden birthday input set: ${dateStr}`);
  401. }
  402. } else if (ageInput) {
  403. if (resolvedAge == null || Number.isNaN(Number(resolvedAge))) {
  404. throw new Error('Age field detected, but no age data provided.');
  405. }
  406. await humanPause(500, 1300);
  407. fillInput(ageInput, String(resolvedAge));
  408. log(`Step 5: Age filled: ${resolvedAge}`);
  409. // Some age-mode pages still submit a hidden birthday field.
  410. // Keep it aligned with generated data so backend validation won't reject.
  411. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  412. if (hiddenBirthday && hasBirthdayData) {
  413. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  414. hiddenBirthday.value = dateStr;
  415. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  416. log(`Step 5: Hidden birthday input set (age mode): ${dateStr}`);
  417. }
  418. } else {
  419. throw new Error('Could not find birthday or age input. URL: ' + location.href);
  420. }
  421. // Click "完成帐户创建" button
  422. await sleep(500);
  423. const completeBtn = document.querySelector('button[type="submit"]')
  424. || await waitForElementByText('button', /完成|create|continue|finish|done|agree/i, 5000).catch(() => null);
  425. // Report complete BEFORE submit (page navigates to add-phone after this)
  426. reportComplete(5);
  427. if (completeBtn) {
  428. await humanPause(500, 1300);
  429. simulateClick(completeBtn);
  430. log('Step 5: Clicked "完成帐户创建"');
  431. }
  432. }