background.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. // background.js — Service Worker: orchestration, state, tab management, message routing
  2. importScripts('data/names.js');
  3. const LOG_PREFIX = '[MultiPage:bg]';
  4. // ============================================================
  5. // State Management (chrome.storage.session)
  6. // ============================================================
  7. const DEFAULT_STATE = {
  8. currentStep: 0,
  9. stepStatuses: {
  10. 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending',
  11. 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
  12. },
  13. oauthUrl: null,
  14. email: null,
  15. password: 'mimashisha0.0',
  16. lastEmailTimestamp: null,
  17. localhostUrl: null,
  18. flowStartTime: null,
  19. tabRegistry: {},
  20. logs: [],
  21. vpsUrl: 'http://154.26.182.181:8317/management.html#/oauth',
  22. mailProvider: 'qq', // 'qq' or '163'
  23. };
  24. async function getState() {
  25. const state = await chrome.storage.session.get(null);
  26. return { ...DEFAULT_STATE, ...state };
  27. }
  28. async function setState(updates) {
  29. console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
  30. await chrome.storage.session.set(updates);
  31. }
  32. async function resetState() {
  33. console.log(LOG_PREFIX, 'Resetting all state');
  34. await chrome.storage.session.clear();
  35. await chrome.storage.session.set({ ...DEFAULT_STATE });
  36. }
  37. // ============================================================
  38. // Tab Registry
  39. // ============================================================
  40. async function getTabRegistry() {
  41. const state = await getState();
  42. return state.tabRegistry || {};
  43. }
  44. async function registerTab(source, tabId) {
  45. const registry = await getTabRegistry();
  46. registry[source] = { tabId, ready: true };
  47. await setState({ tabRegistry: registry });
  48. console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
  49. }
  50. async function isTabAlive(source) {
  51. const registry = await getTabRegistry();
  52. const entry = registry[source];
  53. if (!entry) return false;
  54. try {
  55. await chrome.tabs.get(entry.tabId);
  56. return true;
  57. } catch {
  58. // Tab no longer exists — clean up registry
  59. registry[source] = null;
  60. await setState({ tabRegistry: registry });
  61. return false;
  62. }
  63. }
  64. async function getTabId(source) {
  65. const registry = await getTabRegistry();
  66. return registry[source]?.tabId || null;
  67. }
  68. // ============================================================
  69. // Command Queue (for content scripts not yet ready)
  70. // ============================================================
  71. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  72. function queueCommand(source, message, timeout = 15000) {
  73. return new Promise((resolve, reject) => {
  74. const timer = setTimeout(() => {
  75. pendingCommands.delete(source);
  76. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  77. console.error(LOG_PREFIX, err);
  78. reject(new Error(err));
  79. }, timeout);
  80. pendingCommands.set(source, { message, resolve, reject, timer });
  81. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  82. });
  83. }
  84. function flushCommand(source, tabId) {
  85. const pending = pendingCommands.get(source);
  86. if (pending) {
  87. clearTimeout(pending.timer);
  88. pendingCommands.delete(source);
  89. chrome.tabs.sendMessage(tabId, pending.message).then(pending.resolve).catch(pending.reject);
  90. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  91. }
  92. }
  93. // ============================================================
  94. // Send command to content script (with readiness check)
  95. // ============================================================
  96. async function sendToContentScript(source, message) {
  97. const registry = await getTabRegistry();
  98. const entry = registry[source];
  99. if (!entry || !entry.ready) {
  100. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  101. return queueCommand(source, message);
  102. }
  103. // Verify tab is still alive
  104. const alive = await isTabAlive(source);
  105. if (!alive) {
  106. // Tab was closed — queue the command, it will be sent when tab is reopened
  107. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  108. return queueCommand(source, message);
  109. }
  110. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  111. return chrome.tabs.sendMessage(entry.tabId, message);
  112. }
  113. // ============================================================
  114. // Logging
  115. // ============================================================
  116. async function addLog(message, level = 'info') {
  117. const state = await getState();
  118. const logs = state.logs || [];
  119. const entry = { message, level, timestamp: Date.now() };
  120. logs.push(entry);
  121. // Keep last 500 logs
  122. if (logs.length > 500) logs.splice(0, logs.length - 500);
  123. await setState({ logs });
  124. // Broadcast to side panel
  125. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => {});
  126. }
  127. // ============================================================
  128. // Step Status Management
  129. // ============================================================
  130. async function setStepStatus(step, status) {
  131. const state = await getState();
  132. const statuses = { ...state.stepStatuses };
  133. statuses[step] = status;
  134. await setState({ stepStatuses: statuses, currentStep: step });
  135. // Broadcast to side panel
  136. chrome.runtime.sendMessage({
  137. type: 'STEP_STATUS_CHANGED',
  138. payload: { step, status },
  139. }).catch(() => {});
  140. }
  141. // ============================================================
  142. // Message Handler (central router)
  143. // ============================================================
  144. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  145. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  146. handleMessage(message, sender).then(response => {
  147. sendResponse(response);
  148. }).catch(err => {
  149. console.error(LOG_PREFIX, 'Handler error:', err);
  150. sendResponse({ error: err.message });
  151. });
  152. return true; // async response
  153. });
  154. async function handleMessage(message, sender) {
  155. switch (message.type) {
  156. case 'CONTENT_SCRIPT_READY': {
  157. const tabId = sender.tab?.id;
  158. if (tabId && message.source) {
  159. await registerTab(message.source, tabId);
  160. flushCommand(message.source, tabId);
  161. await addLog(`Content script ready: ${message.source} (tab ${tabId})`);
  162. }
  163. return { ok: true };
  164. }
  165. case 'LOG': {
  166. const { message: msg, level } = message.payload;
  167. await addLog(`[${message.source}] ${msg}`, level);
  168. return { ok: true };
  169. }
  170. case 'STEP_COMPLETE': {
  171. await setStepStatus(message.step, 'completed');
  172. await addLog(`Step ${message.step} completed`, 'ok');
  173. await handleStepData(message.step, message.payload);
  174. notifyStepComplete(message.step, message.payload);
  175. return { ok: true };
  176. }
  177. case 'STEP_ERROR': {
  178. await setStepStatus(message.step, 'failed');
  179. await addLog(`Step ${message.step} failed: ${message.error}`, 'error');
  180. notifyStepError(message.step, message.error);
  181. return { ok: true };
  182. }
  183. case 'GET_STATE': {
  184. return await getState();
  185. }
  186. case 'RESET': {
  187. await resetState();
  188. await addLog('Flow reset', 'info');
  189. return { ok: true };
  190. }
  191. case 'EXECUTE_STEP': {
  192. const step = message.payload.step;
  193. // Save email if provided (from side panel step 3)
  194. if (message.payload.email) {
  195. await setState({ email: message.payload.email });
  196. }
  197. await executeStep(step);
  198. return { ok: true };
  199. }
  200. case 'AUTO_RUN': {
  201. autoRun(); // fire-and-forget, runs in background
  202. return { ok: true };
  203. }
  204. case 'RESUME_AUTO_RUN': {
  205. if (message.payload.email) {
  206. await setState({ email: message.payload.email });
  207. }
  208. resumeAutoRun(); // fire-and-forget
  209. return { ok: true };
  210. }
  211. case 'SAVE_SETTING': {
  212. const updates = {};
  213. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  214. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  215. await setState(updates);
  216. return { ok: true };
  217. }
  218. // Side panel data updates
  219. case 'SAVE_EMAIL': {
  220. await setState({ email: message.payload.email });
  221. return { ok: true };
  222. }
  223. default:
  224. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  225. return { error: `Unknown message type: ${message.type}` };
  226. }
  227. }
  228. // ============================================================
  229. // Step Data Handlers
  230. // ============================================================
  231. async function handleStepData(step, payload) {
  232. switch (step) {
  233. case 1:
  234. if (payload.oauthUrl) {
  235. await setState({ oauthUrl: payload.oauthUrl });
  236. // Broadcast OAuth URL to side panel
  237. chrome.runtime.sendMessage({
  238. type: 'DATA_UPDATED',
  239. payload: { oauthUrl: payload.oauthUrl },
  240. }).catch(() => {});
  241. }
  242. break;
  243. case 3:
  244. if (payload.email) await setState({ email: payload.email });
  245. break;
  246. case 4:
  247. if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
  248. break;
  249. case 8:
  250. if (payload.localhostUrl) {
  251. await setState({ localhostUrl: payload.localhostUrl });
  252. chrome.runtime.sendMessage({
  253. type: 'DATA_UPDATED',
  254. payload: { localhostUrl: payload.localhostUrl },
  255. }).catch(() => {});
  256. }
  257. break;
  258. }
  259. }
  260. // ============================================================
  261. // Step Completion Waiting
  262. // ============================================================
  263. // Map of step -> { resolve, reject } for waiting on step completion
  264. const stepWaiters = new Map();
  265. function waitForStepComplete(step, timeoutMs = 120000) {
  266. return new Promise((resolve, reject) => {
  267. const timer = setTimeout(() => {
  268. stepWaiters.delete(step);
  269. reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
  270. }, timeoutMs);
  271. stepWaiters.set(step, {
  272. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  273. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  274. });
  275. });
  276. }
  277. function notifyStepComplete(step, payload) {
  278. const waiter = stepWaiters.get(step);
  279. if (waiter) waiter.resolve(payload);
  280. }
  281. function notifyStepError(step, error) {
  282. const waiter = stepWaiters.get(step);
  283. if (waiter) waiter.reject(new Error(error));
  284. }
  285. // ============================================================
  286. // Step Execution
  287. // ============================================================
  288. async function executeStep(step) {
  289. console.log(LOG_PREFIX, `Executing step ${step}`);
  290. await setStepStatus(step, 'running');
  291. await addLog(`Step ${step} started`);
  292. const state = await getState();
  293. // Set flow start time on first step
  294. if (step === 1 && !state.flowStartTime) {
  295. await setState({ flowStartTime: Date.now() });
  296. }
  297. try {
  298. switch (step) {
  299. case 1: await executeStep1(state); break;
  300. case 2: await executeStep2(state); break;
  301. case 3: await executeStep3(state); break;
  302. case 4: await executeStep4(state); break;
  303. case 5: await executeStep5(state); break;
  304. case 6: await executeStep6(state); break;
  305. case 7: await executeStep7(state); break;
  306. case 8: await executeStep8(state); break;
  307. case 9: await executeStep9(state); break;
  308. default:
  309. throw new Error(`Unknown step: ${step}`);
  310. }
  311. } catch (err) {
  312. await setStepStatus(step, 'failed');
  313. await addLog(`Step ${step} failed: ${err.message}`, 'error');
  314. }
  315. }
  316. /**
  317. * Execute a step and wait for it to complete before returning.
  318. * @param {number} step
  319. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  320. */
  321. async function executeStepAndWait(step, delayAfter = 2000) {
  322. const promise = waitForStepComplete(step, 120000);
  323. await executeStep(step);
  324. await promise;
  325. // Extra delay for page transitions / DOM updates
  326. if (delayAfter > 0) {
  327. await new Promise(r => setTimeout(r, delayAfter));
  328. }
  329. }
  330. // ============================================================
  331. // Auto Run Flow
  332. // ============================================================
  333. let autoRunActive = false;
  334. async function autoRun() {
  335. if (autoRunActive) {
  336. await addLog('Auto run already in progress', 'warn');
  337. return;
  338. }
  339. autoRunActive = true;
  340. await setState({ autoRunning: true });
  341. chrome.runtime.sendMessage({ type: 'AUTO_RUN_STATUS', payload: { phase: 'running' } }).catch(() => {});
  342. try {
  343. // Phase 1: Steps 1-2 (get OAuth link, open signup)
  344. await addLog('=== Auto Run Phase 1: Get OAuth link & open signup ===', 'info');
  345. await executeStepAndWait(1, 2000);
  346. await executeStepAndWait(2, 2000);
  347. // Pause: ask user to generate DuckDuckGo email
  348. await addLog('=== Auto Run PAUSED: Please paste DuckDuckGo email and click "Continue Auto" ===', 'warn');
  349. chrome.runtime.sendMessage({ type: 'AUTO_RUN_STATUS', payload: { phase: 'waiting_email' } }).catch(() => {});
  350. // Wait here — resumed by RESUME_AUTO_RUN message from side panel
  351. } catch (err) {
  352. await addLog(`Auto run failed at Phase 1: ${err.message}`, 'error');
  353. autoRunActive = false;
  354. await setState({ autoRunning: false });
  355. chrome.runtime.sendMessage({ type: 'AUTO_RUN_STATUS', payload: { phase: 'stopped' } }).catch(() => {});
  356. }
  357. }
  358. async function resumeAutoRun() {
  359. try {
  360. const state = await getState();
  361. if (!state.email) {
  362. await addLog('Cannot resume: no email address. Paste email in Side Panel first.', 'error');
  363. return;
  364. }
  365. // Phase 2: Steps 3-9 (fill form, get codes, login, OAuth, verify)
  366. await addLog('=== Auto Run Phase 2: Register, verify, login, complete OAuth ===', 'info');
  367. await executeStepAndWait(3, 3000); // Fill email/password → page navigates to code input
  368. await executeStepAndWait(4, 2000); // Get signup code from QQ Mail → fill in
  369. await executeStepAndWait(5, 3000); // Fill name/birthday → page navigates to add-phone
  370. await executeStepAndWait(6, 3000); // Login via OAuth URL → fill email/password
  371. await executeStepAndWait(7, 2000); // Get login code from QQ Mail → fill in
  372. await executeStepAndWait(8, 2000); // Click "继续" → localhost redirect captured
  373. await executeStepAndWait(9, 1000); // VPS verify → wait for "认证成功!"
  374. await addLog('=== Auto Run COMPLETE! All 9 steps finished successfully ===', 'ok');
  375. chrome.runtime.sendMessage({ type: 'AUTO_RUN_STATUS', payload: { phase: 'complete' } }).catch(() => {});
  376. } catch (err) {
  377. await addLog(`Auto run failed: ${err.message}`, 'error');
  378. chrome.runtime.sendMessage({ type: 'AUTO_RUN_STATUS', payload: { phase: 'stopped' } }).catch(() => {});
  379. } finally {
  380. autoRunActive = false;
  381. await setState({ autoRunning: false });
  382. }
  383. }
  384. // ============================================================
  385. // Step 1: Get OAuth Link (via vps-panel.js)
  386. // ============================================================
  387. async function executeStep1(state) {
  388. const vpsUrl = state.vpsUrl;
  389. if (!vpsUrl) {
  390. throw new Error('No VPS URL configured. Enter VPS address in Side Panel first.');
  391. }
  392. // Ensure VPS panel tab is open
  393. const alive = await isTabAlive('vps-panel');
  394. if (!alive) {
  395. await addLog(`Step 1: Opening VPS panel: ${vpsUrl.slice(0, 60)}...`);
  396. const tab = await chrome.tabs.create({ url: vpsUrl, active: true });
  397. // Dynamically inject content scripts since VPS URL is configurable
  398. // Wait for page to load, then inject
  399. await new Promise(resolve => {
  400. const listener = (tabId, info) => {
  401. if (tabId === tab.id && info.status === 'complete') {
  402. chrome.tabs.onUpdated.removeListener(listener);
  403. resolve();
  404. }
  405. };
  406. chrome.tabs.onUpdated.addListener(listener);
  407. });
  408. await chrome.scripting.executeScript({
  409. target: { tabId: tab.id },
  410. files: ['content/utils.js', 'content/vps-panel.js'],
  411. });
  412. } else {
  413. const tabId = await getTabId('vps-panel');
  414. if (tabId) await chrome.tabs.update(tabId, { active: true });
  415. }
  416. await sendToContentScript('vps-panel', {
  417. type: 'EXECUTE_STEP',
  418. step: 1,
  419. source: 'background',
  420. payload: {},
  421. });
  422. }
  423. // ============================================================
  424. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  425. // ============================================================
  426. async function executeStep2(state) {
  427. if (!state.oauthUrl) {
  428. throw new Error('No OAuth URL. Complete step 1 first.');
  429. }
  430. await addLog(`Step 2: Opening auth URL in new tab: ${state.oauthUrl.slice(0, 80)}...`);
  431. const tab = await chrome.tabs.create({ url: state.oauthUrl, active: true });
  432. // signup-page.js will auto-inject via manifest content_scripts
  433. // Queue the command — it will flush when script sends READY signal
  434. await sendToContentScript('signup-page', {
  435. type: 'EXECUTE_STEP',
  436. step: 2,
  437. source: 'background',
  438. payload: {},
  439. });
  440. }
  441. // ============================================================
  442. // Step 3: Fill Email & Password (via signup-page.js)
  443. // ============================================================
  444. async function executeStep3(state) {
  445. if (!state.email) {
  446. throw new Error('No email address. Paste email in Side Panel first.');
  447. }
  448. await addLog(`Step 3: Filling email ${state.email} and password`);
  449. await sendToContentScript('signup-page', {
  450. type: 'EXECUTE_STEP',
  451. step: 3,
  452. source: 'background',
  453. payload: { email: state.email },
  454. });
  455. }
  456. // ============================================================
  457. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  458. // ============================================================
  459. function getMailConfig(state) {
  460. const provider = state.mailProvider || 'qq';
  461. if (provider === '163') {
  462. return { source: 'mail-163', url: 'https://mail.163.com/js6/main.jsp?df=mail163_letter#module=mbox.ListModule%7C%7B%22fid%22%3A1%2C%22order%22%3A%22date%22%2C%22desc%22%3Atrue%7D', label: '163 Mail' };
  463. }
  464. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ Mail' };
  465. }
  466. async function executeStep4(state) {
  467. const mail = getMailConfig(state);
  468. const alive = await isTabAlive(mail.source);
  469. if (!alive) {
  470. await addLog(`Step 4: Opening ${mail.label}...`);
  471. await chrome.tabs.create({ url: mail.url, active: true });
  472. } else {
  473. const tabId = await getTabId(mail.source);
  474. if (tabId) await chrome.tabs.update(tabId, { active: true });
  475. }
  476. const result = await sendToContentScript(mail.source, {
  477. type: 'POLL_EMAIL',
  478. step: 4,
  479. source: 'background',
  480. payload: {
  481. filterAfterTimestamp: state.flowStartTime || 0,
  482. senderFilters: ['openai', 'noreply', 'verify', 'auth'],
  483. subjectFilters: ['verify', 'verification', 'code', '验证', 'confirm'],
  484. maxAttempts: 20,
  485. intervalMs: 3000,
  486. },
  487. });
  488. if (result && result.error) {
  489. throw new Error(result.error);
  490. }
  491. if (result && result.code) {
  492. await setState({ lastEmailTimestamp: result.emailTimestamp });
  493. await addLog(`Step 4: Got verification code: ${result.code}`);
  494. // Switch to signup tab and fill code
  495. const signupTabId = await getTabId('signup-page');
  496. if (signupTabId) {
  497. await chrome.tabs.update(signupTabId, { active: true });
  498. await sendToContentScript('signup-page', {
  499. type: 'FILL_CODE',
  500. step: 4,
  501. source: 'background',
  502. payload: { code: result.code },
  503. });
  504. } else {
  505. throw new Error('Signup page tab was closed. Cannot fill verification code.');
  506. }
  507. }
  508. }
  509. // ============================================================
  510. // Step 5: Fill Name & Birthday (via signup-page.js)
  511. // ============================================================
  512. async function executeStep5(state) {
  513. const { firstName, lastName } = generateRandomName();
  514. const { year, month, day } = generateRandomBirthday();
  515. await addLog(`Step 5: Generated name: ${firstName} ${lastName}, Birthday: ${year}-${month}-${day}`);
  516. await sendToContentScript('signup-page', {
  517. type: 'EXECUTE_STEP',
  518. step: 5,
  519. source: 'background',
  520. payload: { firstName, lastName, year, month, day },
  521. });
  522. }
  523. // ============================================================
  524. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  525. // ============================================================
  526. async function executeStep6(state) {
  527. if (!state.oauthUrl) {
  528. throw new Error('No OAuth URL. Complete step 1 first.');
  529. }
  530. if (!state.email) {
  531. throw new Error('No email. Complete step 3 first.');
  532. }
  533. // Open the OAuth URL again in a new tab to start the login flow
  534. // Close the old signup tab first (it's on add-phone page, not needed)
  535. const oldSignupTabId = await getTabId('signup-page');
  536. if (oldSignupTabId) {
  537. try { await chrome.tabs.remove(oldSignupTabId); } catch {}
  538. }
  539. await addLog(`Step 6: Opening OAuth URL for login: ${state.oauthUrl.slice(0, 60)}...`);
  540. await chrome.tabs.create({ url: state.oauthUrl, active: true });
  541. // signup-page.js will inject (same auth.openai.com domain) and handle login
  542. await sendToContentScript('signup-page', {
  543. type: 'EXECUTE_STEP',
  544. step: 6,
  545. source: 'background',
  546. payload: { email: state.email, password: state.password || 'mimashisha0.0' },
  547. });
  548. }
  549. // ============================================================
  550. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  551. // ============================================================
  552. async function executeStep7(state) {
  553. const mail = getMailConfig(state);
  554. const alive = await isTabAlive(mail.source);
  555. if (!alive) {
  556. await addLog(`Step 7: Opening ${mail.label}...`);
  557. await chrome.tabs.create({ url: mail.url, active: true });
  558. } else {
  559. const tabId = await getTabId(mail.source);
  560. if (tabId) await chrome.tabs.update(tabId, { active: true });
  561. }
  562. const result = await sendToContentScript(mail.source, {
  563. type: 'POLL_EMAIL',
  564. step: 7,
  565. source: 'background',
  566. payload: {
  567. filterAfterTimestamp: state.lastEmailTimestamp || state.flowStartTime || 0,
  568. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt'],
  569. subjectFilters: ['verify', 'verification', 'code', '验证', 'confirm', 'login'],
  570. maxAttempts: 20,
  571. intervalMs: 3000,
  572. },
  573. });
  574. if (result && result.error) {
  575. throw new Error(result.error);
  576. }
  577. if (result && result.code) {
  578. await addLog(`Step 7: Got login verification code: ${result.code}`);
  579. // Switch to signup/auth tab and fill code
  580. const signupTabId = await getTabId('signup-page');
  581. if (signupTabId) {
  582. await chrome.tabs.update(signupTabId, { active: true });
  583. await sendToContentScript('signup-page', {
  584. type: 'FILL_CODE',
  585. step: 7,
  586. source: 'background',
  587. payload: { code: result.code },
  588. });
  589. } else {
  590. throw new Error('Auth page tab was closed. Cannot fill verification code.');
  591. }
  592. }
  593. }
  594. // ============================================================
  595. // Step 8: Complete OAuth (webNavigation listener + chatgpt.js navigates)
  596. // ============================================================
  597. let webNavListener = null;
  598. async function executeStep8(state) {
  599. if (!state.oauthUrl) {
  600. throw new Error('No OAuth URL. Complete step 1 first.');
  601. }
  602. await addLog('Step 8: Setting up localhost redirect listener...');
  603. // Register webNavigation listener (scoped to this step)
  604. return new Promise((resolve, reject) => {
  605. const timeout = setTimeout(() => {
  606. if (webNavListener) {
  607. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  608. webNavListener = null;
  609. }
  610. setStepStatus(8, 'failed');
  611. addLog('Step 8: Localhost redirect not captured after 30s. Check if OAuth authorization completed.', 'error');
  612. reject(new Error('Localhost redirect not captured after 30s. Check if OAuth authorization completed.'));
  613. }, 30000);
  614. webNavListener = (details) => {
  615. if (details.url.startsWith('http://localhost')) {
  616. console.log(LOG_PREFIX, `Captured localhost redirect: ${details.url}`);
  617. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  618. webNavListener = null;
  619. clearTimeout(timeout);
  620. setState({ localhostUrl: details.url }).then(() => {
  621. addLog(`Step 8: Captured localhost URL: ${details.url}`, 'ok');
  622. setStepStatus(8, 'completed');
  623. notifyStepComplete(8, { localhostUrl: details.url });
  624. chrome.runtime.sendMessage({
  625. type: 'DATA_UPDATED',
  626. payload: { localhostUrl: details.url },
  627. }).catch(() => {});
  628. resolve();
  629. });
  630. }
  631. };
  632. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  633. // After step 7, the auth page shows a consent screen ("使用 ChatGPT 登录到 Codex")
  634. // with a "继续" button. We need to click it, which triggers the localhost redirect.
  635. (async () => {
  636. try {
  637. const signupTabId = await getTabId('signup-page');
  638. if (signupTabId) {
  639. await chrome.tabs.update(signupTabId, { active: true });
  640. await addLog('Step 8: Switching to auth page, clicking "继续" to complete OAuth...');
  641. await sendToContentScript('signup-page', {
  642. type: 'EXECUTE_STEP',
  643. step: 8,
  644. source: 'background',
  645. payload: {},
  646. });
  647. } else {
  648. // Auth tab was closed, reopen OAuth URL
  649. await chrome.tabs.create({ url: state.oauthUrl, active: true });
  650. await addLog('Step 8: Auth tab closed, reopening OAuth URL...');
  651. await sendToContentScript('signup-page', {
  652. type: 'EXECUTE_STEP',
  653. step: 8,
  654. source: 'background',
  655. payload: {},
  656. });
  657. }
  658. } catch (err) {
  659. clearTimeout(timeout);
  660. if (webNavListener) {
  661. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  662. webNavListener = null;
  663. }
  664. reject(err);
  665. }
  666. })();
  667. });
  668. }
  669. // ============================================================
  670. // Step 9: VPS Verify (via vps-panel.js)
  671. // ============================================================
  672. async function executeStep9(state) {
  673. if (!state.localhostUrl) {
  674. throw new Error('No localhost URL. Complete step 8 first.');
  675. }
  676. const vpsUrl = state.vpsUrl || 'http://154.26.182.181:8317/management.html#/oauth';
  677. // Switch to VPS panel tab
  678. const alive = await isTabAlive('vps-panel');
  679. if (!alive) {
  680. await addLog('Step 9: Opening VPS panel...');
  681. const tab = await chrome.tabs.create({ url: vpsUrl, active: true });
  682. await new Promise(resolve => {
  683. const listener = (tabId, info) => {
  684. if (tabId === tab.id && info.status === 'complete') {
  685. chrome.tabs.onUpdated.removeListener(listener);
  686. resolve();
  687. }
  688. };
  689. chrome.tabs.onUpdated.addListener(listener);
  690. });
  691. await chrome.scripting.executeScript({
  692. target: { tabId: tab.id },
  693. files: ['content/utils.js', 'content/vps-panel.js'],
  694. });
  695. } else {
  696. const tabId = await getTabId('vps-panel');
  697. if (tabId) await chrome.tabs.update(tabId, { active: true });
  698. }
  699. await sendToContentScript('vps-panel', {
  700. type: 'EXECUTE_STEP',
  701. step: 9,
  702. source: 'background',
  703. payload: {},
  704. });
  705. }
  706. // ============================================================
  707. // Open Side Panel on extension icon click
  708. // ============================================================
  709. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });