signup-page.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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') {
  7. handleCommand(message).then(() => {
  8. sendResponse({ ok: true });
  9. }).catch(err => {
  10. reportError(message.step, err.message);
  11. sendResponse({ error: err.message });
  12. });
  13. return true;
  14. }
  15. });
  16. async function handleCommand(message) {
  17. switch (message.type) {
  18. case 'EXECUTE_STEP':
  19. switch (message.step) {
  20. case 2: return await step2_clickRegister();
  21. case 3: return await step3_fillEmailPassword(message.payload);
  22. case 5: return await step5_fillNameBirthday(message.payload);
  23. case 6: return await step6_login(message.payload);
  24. case 8: return await step8_clickContinue();
  25. default: throw new Error(`signup-page.js does not handle step ${message.step}`);
  26. }
  27. case 'FILL_CODE':
  28. // Step 4 = signup code, Step 7 = login code (same handler)
  29. return await fillVerificationCode(message.step, message.payload);
  30. }
  31. }
  32. // ============================================================
  33. // Step 2: Click Register
  34. // ============================================================
  35. async function step2_clickRegister() {
  36. log('Step 2: Looking for Register/Sign up button...');
  37. let registerBtn = null;
  38. try {
  39. registerBtn = await waitForElementByText(
  40. 'a, button, [role="button"], [role="link"]',
  41. /sign\s*up|register|create\s*account|注册/i,
  42. 10000
  43. );
  44. } catch {
  45. // Some pages may have a direct link
  46. try {
  47. registerBtn = await waitForElement('a[href*="signup"], a[href*="register"]', 5000);
  48. } catch {
  49. throw new Error(
  50. 'Could not find Register/Sign up button. ' +
  51. 'Check auth page DOM in DevTools. URL: ' + location.href
  52. );
  53. }
  54. }
  55. reportComplete(2);
  56. simulateClick(registerBtn);
  57. log('Step 2: Clicked Register button');
  58. }
  59. // ============================================================
  60. // Step 3: Fill Email & Password
  61. // ============================================================
  62. async function step3_fillEmailPassword(payload) {
  63. const { email } = payload;
  64. if (!email) throw new Error('No email provided. Paste email in Side Panel first.');
  65. log(`Step 3: Filling email: ${email}`);
  66. // Find email input
  67. let emailInput = null;
  68. try {
  69. emailInput = await waitForElement(
  70. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email"], input[placeholder*="Email"]',
  71. 10000
  72. );
  73. } catch {
  74. throw new Error('Could not find email input field on signup page. URL: ' + location.href);
  75. }
  76. fillInput(emailInput, email);
  77. log('Step 3: Email filled');
  78. // Check if password field is on the same page
  79. let passwordInput = document.querySelector('input[type="password"]');
  80. if (!passwordInput) {
  81. // Need to submit email first to get to password page
  82. log('Step 3: No password field yet, submitting email first...');
  83. const submitBtn = document.querySelector('button[type="submit"]')
  84. || await waitForElementByText('button', /continue|next|submit|继续|下一步/i, 5000).catch(() => null);
  85. if (submitBtn) {
  86. simulateClick(submitBtn);
  87. log('Step 3: Submitted email, waiting for password field...');
  88. await sleep(2000);
  89. }
  90. try {
  91. passwordInput = await waitForElement('input[type="password"]', 10000);
  92. } catch {
  93. throw new Error('Could not find password input after submitting email. URL: ' + location.href);
  94. }
  95. }
  96. if (!payload.password) throw new Error('No password provided. Step 3 requires a generated password.');
  97. fillInput(passwordInput, payload.password);
  98. log('Step 3: Password filled');
  99. // Report complete BEFORE submit, because submit causes page navigation
  100. // which kills the content script connection
  101. reportComplete(3, { email });
  102. // Submit the form (page will navigate away after this)
  103. await sleep(500);
  104. const submitBtn = document.querySelector('button[type="submit"]')
  105. || await waitForElementByText('button', /continue|sign\s*up|submit|注册|创建|create/i, 5000).catch(() => null);
  106. if (submitBtn) {
  107. simulateClick(submitBtn);
  108. log('Step 3: Form submitted');
  109. }
  110. }
  111. // ============================================================
  112. // Fill Verification Code (used by step 4 and step 7)
  113. // ============================================================
  114. async function fillVerificationCode(step, payload) {
  115. const { code } = payload;
  116. if (!code) throw new Error('No verification code provided.');
  117. log(`Step ${step}: Filling verification code: ${code}`);
  118. // Find code input — could be a single input or multiple separate inputs
  119. let codeInput = null;
  120. try {
  121. codeInput = await waitForElement(
  122. 'input[name="code"], input[name="otp"], input[type="text"][maxlength="6"], input[aria-label*="code"], input[placeholder*="code"], input[placeholder*="Code"], input[inputmode="numeric"]',
  123. 10000
  124. );
  125. } catch {
  126. // Check for multiple single-digit inputs (common pattern)
  127. const singleInputs = document.querySelectorAll('input[maxlength="1"]');
  128. if (singleInputs.length >= 6) {
  129. log(`Step ${step}: Found single-digit code inputs, filling individually...`);
  130. for (let i = 0; i < 6 && i < singleInputs.length; i++) {
  131. fillInput(singleInputs[i], code[i]);
  132. await sleep(100);
  133. }
  134. await sleep(1000);
  135. reportComplete(step);
  136. return;
  137. }
  138. throw new Error('Could not find verification code input. URL: ' + location.href);
  139. }
  140. fillInput(codeInput, code);
  141. log(`Step ${step}: Code filled`);
  142. // Report complete BEFORE submit (page may navigate away)
  143. reportComplete(step);
  144. // Submit
  145. await sleep(500);
  146. const submitBtn = document.querySelector('button[type="submit"]')
  147. || await waitForElementByText('button', /verify|confirm|submit|continue|确认|验证/i, 5000).catch(() => null);
  148. if (submitBtn) {
  149. simulateClick(submitBtn);
  150. log(`Step ${step}: Verification submitted`);
  151. }
  152. }
  153. // ============================================================
  154. // Step 6: Login with registered account (on OAuth auth page)
  155. // ============================================================
  156. async function step6_login(payload) {
  157. const { email, password } = payload;
  158. if (!email) throw new Error('No email provided for login.');
  159. log(`Step 6: Logging in with ${email}...`);
  160. // Wait for email input on the auth page
  161. let emailInput = null;
  162. try {
  163. emailInput = await waitForElement(
  164. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email" i], input[placeholder*="Email"]',
  165. 15000
  166. );
  167. } catch {
  168. throw new Error('Could not find email input on login page. URL: ' + location.href);
  169. }
  170. fillInput(emailInput, email);
  171. log('Step 6: Email filled');
  172. // Submit email
  173. await sleep(500);
  174. const submitBtn1 = document.querySelector('button[type="submit"]')
  175. || await waitForElementByText('button', /continue|next|submit|继续|下一步/i, 5000).catch(() => null);
  176. if (submitBtn1) {
  177. simulateClick(submitBtn1);
  178. log('Step 6: Submitted email');
  179. }
  180. await sleep(2000);
  181. // Check for password field
  182. const passwordInput = document.querySelector('input[type="password"]');
  183. if (passwordInput) {
  184. log('Step 6: Password field found, filling password...');
  185. fillInput(passwordInput, password);
  186. await sleep(500);
  187. const submitBtn2 = document.querySelector('button[type="submit"]')
  188. || await waitForElementByText('button', /continue|log\s*in|submit|sign\s*in|登录|继续/i, 5000).catch(() => null);
  189. // Report complete BEFORE submit in case page navigates
  190. reportComplete(6, { needsOTP: true });
  191. if (submitBtn2) {
  192. simulateClick(submitBtn2);
  193. log('Step 6: Submitted password, may need verification code (step 7)');
  194. }
  195. return;
  196. }
  197. // No password field — OTP flow
  198. log('Step 6: No password field. OTP flow or auto-redirect.');
  199. reportComplete(6, { needsOTP: true });
  200. }
  201. // ============================================================
  202. // Step 8: Click "继续" on OAuth consent page
  203. // ============================================================
  204. // After login + verification, page shows:
  205. // "使用 ChatGPT 登录到 Codex" with a "继续" submit button.
  206. // Clicking it triggers redirect to localhost URL.
  207. async function step8_clickContinue() {
  208. log('Step 8: Looking for OAuth consent "继续" button...');
  209. // Wait for the consent page to be ready
  210. // Look for the submit button with text "继续" or data-dd-action-name="Continue"
  211. let continueBtn = null;
  212. try {
  213. continueBtn = await waitForElement(
  214. 'button[type="submit"][data-dd-action-name="Continue"], button[type="submit"]._primary_3rdp0_107',
  215. 10000
  216. );
  217. } catch {
  218. try {
  219. continueBtn = await waitForElementByText('button', /继续|Continue/, 5000);
  220. } catch {
  221. throw new Error('Could not find "继续" button on OAuth consent page. URL: ' + location.href);
  222. }
  223. }
  224. log('Step 8: Found "继续" button, clicking...');
  225. // Use native .click() — simulateClick (dispatchEvent) may not trigger form submit
  226. continueBtn.click();
  227. log('Step 8: Clicked via .click()');
  228. // Also try submitting the form directly as a fallback
  229. await sleep(500);
  230. const form = continueBtn.closest('form');
  231. if (form) {
  232. form.requestSubmit(continueBtn);
  233. log('Step 8: Also triggered form.requestSubmit()');
  234. }
  235. log('Step 8: Redirecting to localhost... (background will capture URL)');
  236. // Don't reportComplete — background handles it via webNavigation listener
  237. }
  238. // ============================================================
  239. // Step 5: Fill Name & Birthday
  240. // ============================================================
  241. async function step5_fillNameBirthday(payload) {
  242. const { firstName, lastName, year, month, day } = payload;
  243. if (!firstName || !lastName) throw new Error('No name data provided.');
  244. const fullName = `${firstName} ${lastName}`;
  245. log(`Step 5: Filling name: ${fullName}, Birthday: ${year}-${String(month).padStart(2,'0')}-${String(day).padStart(2,'0')}`);
  246. // Actual DOM structure:
  247. // - Full name: <input name="name" placeholder="全名" type="text">
  248. // - Birthday: React Aria DateField with 3 spinbutton divs (year/month/day)
  249. // + <input type="hidden" name="birthday" value="2026-04-05">
  250. // --- Full Name (single field, not first+last) ---
  251. let nameInput = null;
  252. try {
  253. nameInput = await waitForElement(
  254. 'input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]',
  255. 10000
  256. );
  257. } catch {
  258. throw new Error('Could not find name input. URL: ' + location.href);
  259. }
  260. fillInput(nameInput, fullName);
  261. log(`Step 5: Name filled: ${fullName}`);
  262. // --- Birthday (React Aria DateField with spinbutton segments) ---
  263. // The date field has three contenteditable divs with role="spinbutton"
  264. // and data-type="year", data-type="month", data-type="day"
  265. // There's also a hidden input[name="birthday"] that stores the actual value
  266. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  267. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  268. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  269. if (yearSpinner && monthSpinner && daySpinner) {
  270. log('Step 5: Found React Aria DateField spinbuttons');
  271. // Helper to set a spinbutton value via focus + keyboard input
  272. async function setSpinButton(el, value) {
  273. el.focus();
  274. await sleep(100);
  275. // Select all existing text
  276. document.execCommand('selectAll', false, null);
  277. await sleep(50);
  278. // Type the new value digit by digit
  279. const valueStr = String(value);
  280. for (const char of valueStr) {
  281. el.dispatchEvent(new KeyboardEvent('keydown', { key: char, code: `Digit${char}`, bubbles: true }));
  282. el.dispatchEvent(new KeyboardEvent('keypress', { key: char, code: `Digit${char}`, bubbles: true }));
  283. // Also use InputEvent for React Aria
  284. el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: char, bubbles: true }));
  285. el.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: char, bubbles: true }));
  286. await sleep(50);
  287. }
  288. el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab', code: 'Tab', bubbles: true }));
  289. el.blur();
  290. await sleep(100);
  291. }
  292. await setSpinButton(yearSpinner, year);
  293. log(`Step 5: Year set: ${year}`);
  294. await setSpinButton(monthSpinner, String(month).padStart(2, '0'));
  295. log(`Step 5: Month set: ${month}`);
  296. await setSpinButton(daySpinner, String(day).padStart(2, '0'));
  297. log(`Step 5: Day set: ${day}`);
  298. // Also update the hidden input directly as a safety measure
  299. const hiddenBirthday = document.querySelector('input[type="hidden"][name="birthday"]');
  300. if (hiddenBirthday) {
  301. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  302. hiddenBirthday.value = dateStr;
  303. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  304. log(`Step 5: Hidden birthday input set: ${dateStr}`);
  305. }
  306. } else {
  307. // Fallback: try setting hidden input directly
  308. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  309. if (hiddenBirthday) {
  310. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  311. hiddenBirthday.value = dateStr;
  312. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  313. log(`Step 5: Birthday set via hidden input: ${dateStr}`);
  314. } else {
  315. log('Step 5: WARNING - Could not find birthday fields. May need to adjust selectors.', 'warn');
  316. }
  317. }
  318. // Click "完成帐户创建" button
  319. await sleep(500);
  320. const completeBtn = document.querySelector('button[type="submit"]')
  321. || await waitForElementByText('button', /完成|create|continue|finish|done|agree/i, 5000).catch(() => null);
  322. // Report complete BEFORE submit (page navigates to add-phone after this)
  323. reportComplete(5);
  324. if (completeBtn) {
  325. simulateClick(completeBtn);
  326. log('Step 5: Clicked "完成帐户创建"');
  327. }
  328. }