signup-page.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. await sleep(2000);
  202. // Check for password field
  203. const passwordInput = document.querySelector('input[type="password"]');
  204. if (passwordInput) {
  205. log('Step 6: Password field found, filling password...');
  206. await humanPause(550, 1450);
  207. fillInput(passwordInput, password);
  208. await sleep(500);
  209. const submitBtn2 = document.querySelector('button[type="submit"]')
  210. || await waitForElementByText('button', /continue|log\s*in|submit|sign\s*in|登录|继续/i, 5000).catch(() => null);
  211. // Report complete BEFORE submit in case page navigates
  212. reportComplete(6, { needsOTP: true });
  213. if (submitBtn2) {
  214. await humanPause(450, 1200);
  215. simulateClick(submitBtn2);
  216. log('Step 6: Submitted password, may need verification code (step 7)');
  217. }
  218. return;
  219. }
  220. // No password field — OTP flow
  221. log('Step 6: No password field. OTP flow or auto-redirect.');
  222. reportComplete(6, { needsOTP: true });
  223. }
  224. // ============================================================
  225. // Step 8: Find "继续" on OAuth consent page for debugger click
  226. // ============================================================
  227. // After login + verification, page shows:
  228. // "使用 ChatGPT 登录到 Codex" with a "继续" submit button.
  229. // Background performs the actual click through the debugger Input API.
  230. async function step8_findAndClick() {
  231. log('Step 8: Looking for OAuth consent "继续" button...');
  232. const continueBtn = await findContinueButton();
  233. await waitForButtonEnabled(continueBtn);
  234. await humanPause(350, 900);
  235. continueBtn.scrollIntoView({ behavior: 'smooth', block: 'center' });
  236. continueBtn.focus();
  237. await sleep(250);
  238. const rect = getSerializableRect(continueBtn);
  239. log('Step 8: Found "继续" button and prepared debugger click coordinates.');
  240. return {
  241. rect,
  242. buttonText: (continueBtn.textContent || '').trim(),
  243. url: location.href,
  244. };
  245. }
  246. async function findContinueButton() {
  247. try {
  248. return await waitForElement(
  249. 'button[type="submit"][data-dd-action-name="Continue"], button[type="submit"]._primary_3rdp0_107',
  250. 10000
  251. );
  252. } catch {
  253. try {
  254. return await waitForElementByText('button', /继续|Continue/, 5000);
  255. } catch {
  256. throw new Error('Could not find "继续" button on OAuth consent page. URL: ' + location.href);
  257. }
  258. }
  259. }
  260. async function waitForButtonEnabled(button, timeout = 8000) {
  261. const start = Date.now();
  262. while (Date.now() - start < timeout) {
  263. throwIfStopped();
  264. if (isButtonEnabled(button)) return;
  265. await sleep(150);
  266. }
  267. throw new Error('"继续" button stayed disabled for too long. URL: ' + location.href);
  268. }
  269. function isButtonEnabled(button) {
  270. return Boolean(button)
  271. && !button.disabled
  272. && button.getAttribute('aria-disabled') !== 'true';
  273. }
  274. function getSerializableRect(el) {
  275. const rect = el.getBoundingClientRect();
  276. if (!rect.width || !rect.height) {
  277. throw new Error('"继续" button has no clickable size after scrolling. URL: ' + location.href);
  278. }
  279. return {
  280. left: rect.left,
  281. top: rect.top,
  282. width: rect.width,
  283. height: rect.height,
  284. centerX: rect.left + (rect.width / 2),
  285. centerY: rect.top + (rect.height / 2),
  286. };
  287. }
  288. // ============================================================
  289. // Step 5: Fill Name & Birthday / Age
  290. // ============================================================
  291. async function step5_fillNameBirthday(payload) {
  292. const { firstName, lastName, age, year, month, day } = payload;
  293. if (!firstName || !lastName) throw new Error('No name data provided.');
  294. const resolvedAge = age ?? (year ? new Date().getFullYear() - Number(year) : null);
  295. const hasBirthdayData = [year, month, day].every(value => value != null && !Number.isNaN(Number(value)));
  296. if (!hasBirthdayData && (resolvedAge == null || Number.isNaN(Number(resolvedAge)))) {
  297. throw new Error('No birthday or age data provided.');
  298. }
  299. const fullName = `${firstName} ${lastName}`;
  300. log(`Step 5: Filling name: ${fullName}`);
  301. // Actual DOM structure:
  302. // - Full name: <input name="name" placeholder="全名" type="text">
  303. // - Birthday: React Aria DateField or hidden input[name="birthday"]
  304. // - Age: <input name="age" type="text|number">
  305. // --- Full Name (single field, not first+last) ---
  306. let nameInput = null;
  307. try {
  308. nameInput = await waitForElement(
  309. 'input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]',
  310. 10000
  311. );
  312. } catch {
  313. throw new Error('Could not find name input. URL: ' + location.href);
  314. }
  315. await humanPause(500, 1300);
  316. fillInput(nameInput, fullName);
  317. log(`Step 5: Name filled: ${fullName}`);
  318. let birthdayMode = false;
  319. let ageInput = null;
  320. for (let i = 0; i < 100; i++) {
  321. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  322. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  323. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  324. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  325. ageInput = document.querySelector('input[name="age"]');
  326. if ((yearSpinner && monthSpinner && daySpinner) || hiddenBirthday) {
  327. birthdayMode = true;
  328. break;
  329. }
  330. if (ageInput) break;
  331. await sleep(100);
  332. }
  333. if (birthdayMode) {
  334. if (!hasBirthdayData) {
  335. throw new Error('Birthday field detected, but no birthday data provided.');
  336. }
  337. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  338. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  339. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  340. if (yearSpinner && monthSpinner && daySpinner) {
  341. log('Step 5: Birthday fields detected, filling birthday...');
  342. async function setSpinButton(el, value) {
  343. el.focus();
  344. await sleep(100);
  345. document.execCommand('selectAll', false, null);
  346. await sleep(50);
  347. const valueStr = String(value);
  348. for (const char of valueStr) {
  349. el.dispatchEvent(new KeyboardEvent('keydown', { key: char, code: `Digit${char}`, bubbles: true }));
  350. el.dispatchEvent(new KeyboardEvent('keypress', { key: char, code: `Digit${char}`, bubbles: true }));
  351. el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: char, bubbles: true }));
  352. el.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: char, bubbles: true }));
  353. await sleep(50);
  354. }
  355. el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab', code: 'Tab', bubbles: true }));
  356. el.blur();
  357. await sleep(100);
  358. }
  359. await humanPause(450, 1100);
  360. await setSpinButton(yearSpinner, year);
  361. await humanPause(250, 650);
  362. await setSpinButton(monthSpinner, String(month).padStart(2, '0'));
  363. await humanPause(250, 650);
  364. await setSpinButton(daySpinner, String(day).padStart(2, '0'));
  365. log(`Step 5: Birthday filled: ${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
  366. }
  367. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  368. if (hiddenBirthday) {
  369. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  370. hiddenBirthday.value = dateStr;
  371. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  372. log(`Step 5: Hidden birthday input set: ${dateStr}`);
  373. }
  374. } else if (ageInput) {
  375. if (resolvedAge == null || Number.isNaN(Number(resolvedAge))) {
  376. throw new Error('Age field detected, but no age data provided.');
  377. }
  378. await humanPause(500, 1300);
  379. fillInput(ageInput, String(resolvedAge));
  380. log(`Step 5: Age filled: ${resolvedAge}`);
  381. } else {
  382. throw new Error('Could not find birthday or age input. URL: ' + location.href);
  383. }
  384. // Click "完成帐户创建" button
  385. await sleep(500);
  386. const completeBtn = document.querySelector('button[type="submit"]')
  387. || await waitForElementByText('button', /完成|create|continue|finish|done|agree/i, 5000).catch(() => null);
  388. // Report complete BEFORE submit (page navigates to add-phone after this)
  389. reportComplete(5);
  390. if (completeBtn) {
  391. await humanPause(500, 1300);
  392. simulateClick(completeBtn);
  393. log('Step 5: Clicked "完成帐户创建"');
  394. }
  395. }