background.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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: '163', // '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. const totalRuns = message.payload?.totalRuns || 1;
  202. autoRunLoop(totalRuns); // fire-and-forget
  203. return { ok: true };
  204. }
  205. case 'RESUME_AUTO_RUN': {
  206. if (message.payload.email) {
  207. await setState({ email: message.payload.email });
  208. }
  209. resumeAutoRun(); // fire-and-forget
  210. return { ok: true };
  211. }
  212. case 'SAVE_SETTING': {
  213. const updates = {};
  214. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  215. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  216. await setState(updates);
  217. return { ok: true };
  218. }
  219. // Side panel data updates
  220. case 'SAVE_EMAIL': {
  221. await setState({ email: message.payload.email });
  222. return { ok: true };
  223. }
  224. default:
  225. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  226. return { error: `Unknown message type: ${message.type}` };
  227. }
  228. }
  229. // ============================================================
  230. // Step Data Handlers
  231. // ============================================================
  232. async function handleStepData(step, payload) {
  233. switch (step) {
  234. case 1:
  235. if (payload.oauthUrl) {
  236. await setState({ oauthUrl: payload.oauthUrl });
  237. // Broadcast OAuth URL to side panel
  238. chrome.runtime.sendMessage({
  239. type: 'DATA_UPDATED',
  240. payload: { oauthUrl: payload.oauthUrl },
  241. }).catch(() => {});
  242. }
  243. break;
  244. case 3:
  245. if (payload.email) await setState({ email: payload.email });
  246. break;
  247. case 4:
  248. if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
  249. break;
  250. case 8:
  251. if (payload.localhostUrl) {
  252. await setState({ localhostUrl: payload.localhostUrl });
  253. chrome.runtime.sendMessage({
  254. type: 'DATA_UPDATED',
  255. payload: { localhostUrl: payload.localhostUrl },
  256. }).catch(() => {});
  257. }
  258. break;
  259. }
  260. }
  261. // ============================================================
  262. // Step Completion Waiting
  263. // ============================================================
  264. // Map of step -> { resolve, reject } for waiting on step completion
  265. const stepWaiters = new Map();
  266. function waitForStepComplete(step, timeoutMs = 120000) {
  267. return new Promise((resolve, reject) => {
  268. const timer = setTimeout(() => {
  269. stepWaiters.delete(step);
  270. reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
  271. }, timeoutMs);
  272. stepWaiters.set(step, {
  273. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  274. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  275. });
  276. });
  277. }
  278. function notifyStepComplete(step, payload) {
  279. const waiter = stepWaiters.get(step);
  280. if (waiter) waiter.resolve(payload);
  281. }
  282. function notifyStepError(step, error) {
  283. const waiter = stepWaiters.get(step);
  284. if (waiter) waiter.reject(new Error(error));
  285. }
  286. // ============================================================
  287. // Step Execution
  288. // ============================================================
  289. async function executeStep(step) {
  290. console.log(LOG_PREFIX, `Executing step ${step}`);
  291. await setStepStatus(step, 'running');
  292. await addLog(`Step ${step} started`);
  293. const state = await getState();
  294. // Set flow start time on first step
  295. if (step === 1 && !state.flowStartTime) {
  296. await setState({ flowStartTime: Date.now() });
  297. }
  298. try {
  299. switch (step) {
  300. case 1: await executeStep1(state); break;
  301. case 2: await executeStep2(state); break;
  302. case 3: await executeStep3(state); break;
  303. case 4: await executeStep4(state); break;
  304. case 5: await executeStep5(state); break;
  305. case 6: await executeStep6(state); break;
  306. case 7: await executeStep7(state); break;
  307. case 8: await executeStep8(state); break;
  308. case 9: await executeStep9(state); break;
  309. default:
  310. throw new Error(`Unknown step: ${step}`);
  311. }
  312. } catch (err) {
  313. await setStepStatus(step, 'failed');
  314. await addLog(`Step ${step} failed: ${err.message}`, 'error');
  315. }
  316. }
  317. /**
  318. * Execute a step and wait for it to complete before returning.
  319. * @param {number} step
  320. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  321. */
  322. async function executeStepAndWait(step, delayAfter = 2000) {
  323. const promise = waitForStepComplete(step, 120000);
  324. await executeStep(step);
  325. await promise;
  326. // Extra delay for page transitions / DOM updates
  327. if (delayAfter > 0) {
  328. await new Promise(r => setTimeout(r, delayAfter));
  329. }
  330. }
  331. // ============================================================
  332. // Auto Run Flow
  333. // ============================================================
  334. let autoRunActive = false;
  335. let autoRunCurrentRun = 0;
  336. let autoRunTotalRuns = 1;
  337. // Outer loop: runs the full flow N times
  338. async function autoRunLoop(totalRuns) {
  339. if (autoRunActive) {
  340. await addLog('Auto run already in progress', 'warn');
  341. return;
  342. }
  343. autoRunActive = true;
  344. autoRunTotalRuns = totalRuns;
  345. await setState({ autoRunning: true });
  346. for (let run = 1; run <= totalRuns; run++) {
  347. autoRunCurrentRun = run;
  348. if (run > 1) {
  349. // Reset state for next run (keep vpsUrl, mailProvider settings)
  350. await addLog(`=== Resetting for run ${run}/${totalRuns} ===`, 'info');
  351. const state = await getState();
  352. const keepSettings = { vpsUrl: state.vpsUrl, mailProvider: state.mailProvider };
  353. await resetState();
  354. await setState(keepSettings);
  355. // Broadcast reset to side panel
  356. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => {});
  357. await new Promise(r => setTimeout(r, 1000));
  358. }
  359. await addLog(`=== Auto Run ${run}/${totalRuns} — Phase 1: Get OAuth link & open signup ===`, 'info');
  360. const status = (phase) => ({ type: 'AUTO_RUN_STATUS', payload: { phase, currentRun: run, totalRuns } });
  361. try {
  362. chrome.runtime.sendMessage(status('running')).catch(() => {});
  363. await executeStepAndWait(1, 2000);
  364. await executeStepAndWait(2, 2000);
  365. // Pause for email
  366. await addLog(`=== Run ${run}/${totalRuns} PAUSED: Paste DuckDuckGo email, click Continue ===`, 'warn');
  367. chrome.runtime.sendMessage(status('waiting_email')).catch(() => {});
  368. // Wait for RESUME_AUTO_RUN — sets a promise that resumeAutoRun resolves
  369. await waitForResume();
  370. const state = await getState();
  371. if (!state.email) {
  372. await addLog('Cannot resume: no email address.', 'error');
  373. break;
  374. }
  375. await addLog(`=== Run ${run}/${totalRuns} — Phase 2: Register, verify, login, complete ===`, 'info');
  376. chrome.runtime.sendMessage(status('running')).catch(() => {});
  377. await executeStepAndWait(3, 3000);
  378. await executeStepAndWait(4, 2000);
  379. await executeStepAndWait(5, 3000);
  380. await executeStepAndWait(6, 3000);
  381. await executeStepAndWait(7, 2000);
  382. await executeStepAndWait(8, 2000);
  383. await executeStepAndWait(9, 1000);
  384. await addLog(`=== Run ${run}/${totalRuns} COMPLETE! ===`, 'ok');
  385. } catch (err) {
  386. await addLog(`Run ${run}/${totalRuns} failed: ${err.message}`, 'error');
  387. chrome.runtime.sendMessage(status('stopped')).catch(() => {});
  388. break; // Stop on error
  389. }
  390. }
  391. await addLog(`=== All ${autoRunTotalRuns} runs finished ===`, 'ok');
  392. chrome.runtime.sendMessage({ type: 'AUTO_RUN_STATUS', payload: { phase: 'complete', currentRun: autoRunCurrentRun, totalRuns: autoRunTotalRuns } }).catch(() => {});
  393. autoRunActive = false;
  394. await setState({ autoRunning: false });
  395. }
  396. // Promise-based pause/resume mechanism
  397. let resumeResolver = null;
  398. function waitForResume() {
  399. return new Promise((resolve) => {
  400. resumeResolver = resolve;
  401. });
  402. }
  403. async function resumeAutoRun() {
  404. const state = await getState();
  405. if (!state.email) {
  406. await addLog('Cannot resume: no email address. Paste email in Side Panel first.', 'error');
  407. return;
  408. }
  409. if (resumeResolver) {
  410. resumeResolver();
  411. resumeResolver = null;
  412. }
  413. }
  414. // ============================================================
  415. // Step 1: Get OAuth Link (via vps-panel.js)
  416. // ============================================================
  417. async function executeStep1(state) {
  418. const vpsUrl = state.vpsUrl;
  419. if (!vpsUrl) {
  420. throw new Error('No VPS URL configured. Enter VPS address in Side Panel first.');
  421. }
  422. // Ensure VPS panel tab is open
  423. const alive = await isTabAlive('vps-panel');
  424. if (!alive) {
  425. await addLog(`Step 1: Opening VPS panel: ${vpsUrl.slice(0, 60)}...`);
  426. const tab = await chrome.tabs.create({ url: vpsUrl, active: true });
  427. // Dynamically inject content scripts since VPS URL is configurable
  428. // Wait for page to load, then inject
  429. await new Promise(resolve => {
  430. const listener = (tabId, info) => {
  431. if (tabId === tab.id && info.status === 'complete') {
  432. chrome.tabs.onUpdated.removeListener(listener);
  433. resolve();
  434. }
  435. };
  436. chrome.tabs.onUpdated.addListener(listener);
  437. });
  438. await chrome.scripting.executeScript({
  439. target: { tabId: tab.id },
  440. files: ['content/utils.js', 'content/vps-panel.js'],
  441. });
  442. } else {
  443. const tabId = await getTabId('vps-panel');
  444. if (tabId) await chrome.tabs.update(tabId, { active: true });
  445. }
  446. await sendToContentScript('vps-panel', {
  447. type: 'EXECUTE_STEP',
  448. step: 1,
  449. source: 'background',
  450. payload: {},
  451. });
  452. }
  453. // ============================================================
  454. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  455. // ============================================================
  456. async function executeStep2(state) {
  457. if (!state.oauthUrl) {
  458. throw new Error('No OAuth URL. Complete step 1 first.');
  459. }
  460. await addLog(`Step 2: Opening auth URL in new tab: ${state.oauthUrl.slice(0, 80)}...`);
  461. const tab = await chrome.tabs.create({ url: state.oauthUrl, active: true });
  462. // signup-page.js will auto-inject via manifest content_scripts
  463. // Queue the command — it will flush when script sends READY signal
  464. await sendToContentScript('signup-page', {
  465. type: 'EXECUTE_STEP',
  466. step: 2,
  467. source: 'background',
  468. payload: {},
  469. });
  470. }
  471. // ============================================================
  472. // Step 3: Fill Email & Password (via signup-page.js)
  473. // ============================================================
  474. async function executeStep3(state) {
  475. if (!state.email) {
  476. throw new Error('No email address. Paste email in Side Panel first.');
  477. }
  478. await addLog(`Step 3: Filling email ${state.email} and password`);
  479. await sendToContentScript('signup-page', {
  480. type: 'EXECUTE_STEP',
  481. step: 3,
  482. source: 'background',
  483. payload: { email: state.email },
  484. });
  485. }
  486. // ============================================================
  487. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  488. // ============================================================
  489. function getMailConfig(state) {
  490. const provider = state.mailProvider || 'qq';
  491. if (provider === '163') {
  492. 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' };
  493. }
  494. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ Mail' };
  495. }
  496. async function executeStep4(state) {
  497. const mail = getMailConfig(state);
  498. const alive = await isTabAlive(mail.source);
  499. if (!alive) {
  500. await addLog(`Step 4: Opening ${mail.label}...`);
  501. await chrome.tabs.create({ url: mail.url, active: true });
  502. } else {
  503. const tabId = await getTabId(mail.source);
  504. if (tabId) await chrome.tabs.update(tabId, { active: true });
  505. }
  506. const result = await sendToContentScript(mail.source, {
  507. type: 'POLL_EMAIL',
  508. step: 4,
  509. source: 'background',
  510. payload: {
  511. filterAfterTimestamp: state.flowStartTime || 0,
  512. senderFilters: ['openai', 'noreply', 'verify', 'auth'],
  513. subjectFilters: ['verify', 'verification', 'code', '验证', 'confirm'],
  514. maxAttempts: 20,
  515. intervalMs: 3000,
  516. },
  517. });
  518. if (result && result.error) {
  519. throw new Error(result.error);
  520. }
  521. if (result && result.code) {
  522. await setState({ lastEmailTimestamp: result.emailTimestamp });
  523. await addLog(`Step 4: Got verification code: ${result.code}`);
  524. // Switch to signup tab and fill code
  525. const signupTabId = await getTabId('signup-page');
  526. if (signupTabId) {
  527. await chrome.tabs.update(signupTabId, { active: true });
  528. await sendToContentScript('signup-page', {
  529. type: 'FILL_CODE',
  530. step: 4,
  531. source: 'background',
  532. payload: { code: result.code },
  533. });
  534. } else {
  535. throw new Error('Signup page tab was closed. Cannot fill verification code.');
  536. }
  537. }
  538. }
  539. // ============================================================
  540. // Step 5: Fill Name & Birthday (via signup-page.js)
  541. // ============================================================
  542. async function executeStep5(state) {
  543. const { firstName, lastName } = generateRandomName();
  544. const { year, month, day } = generateRandomBirthday();
  545. await addLog(`Step 5: Generated name: ${firstName} ${lastName}, Birthday: ${year}-${month}-${day}`);
  546. await sendToContentScript('signup-page', {
  547. type: 'EXECUTE_STEP',
  548. step: 5,
  549. source: 'background',
  550. payload: { firstName, lastName, year, month, day },
  551. });
  552. }
  553. // ============================================================
  554. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  555. // ============================================================
  556. async function executeStep6(state) {
  557. if (!state.oauthUrl) {
  558. throw new Error('No OAuth URL. Complete step 1 first.');
  559. }
  560. if (!state.email) {
  561. throw new Error('No email. Complete step 3 first.');
  562. }
  563. // Open the OAuth URL again in a new tab to start the login flow
  564. // Close the old signup tab first (it's on add-phone page, not needed)
  565. const oldSignupTabId = await getTabId('signup-page');
  566. if (oldSignupTabId) {
  567. try { await chrome.tabs.remove(oldSignupTabId); } catch {}
  568. }
  569. await addLog(`Step 6: Opening OAuth URL for login: ${state.oauthUrl.slice(0, 60)}...`);
  570. await chrome.tabs.create({ url: state.oauthUrl, active: true });
  571. // signup-page.js will inject (same auth.openai.com domain) and handle login
  572. await sendToContentScript('signup-page', {
  573. type: 'EXECUTE_STEP',
  574. step: 6,
  575. source: 'background',
  576. payload: { email: state.email, password: state.password || 'mimashisha0.0' },
  577. });
  578. }
  579. // ============================================================
  580. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  581. // ============================================================
  582. async function executeStep7(state) {
  583. const mail = getMailConfig(state);
  584. const alive = await isTabAlive(mail.source);
  585. if (!alive) {
  586. await addLog(`Step 7: Opening ${mail.label}...`);
  587. await chrome.tabs.create({ url: mail.url, active: true });
  588. } else {
  589. const tabId = await getTabId(mail.source);
  590. if (tabId) await chrome.tabs.update(tabId, { active: true });
  591. }
  592. const result = await sendToContentScript(mail.source, {
  593. type: 'POLL_EMAIL',
  594. step: 7,
  595. source: 'background',
  596. payload: {
  597. filterAfterTimestamp: state.lastEmailTimestamp || state.flowStartTime || 0,
  598. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt'],
  599. subjectFilters: ['verify', 'verification', 'code', '验证', 'confirm', 'login'],
  600. maxAttempts: 20,
  601. intervalMs: 3000,
  602. },
  603. });
  604. if (result && result.error) {
  605. throw new Error(result.error);
  606. }
  607. if (result && result.code) {
  608. await addLog(`Step 7: Got login verification code: ${result.code}`);
  609. // Switch to signup/auth tab and fill code
  610. const signupTabId = await getTabId('signup-page');
  611. if (signupTabId) {
  612. await chrome.tabs.update(signupTabId, { active: true });
  613. await sendToContentScript('signup-page', {
  614. type: 'FILL_CODE',
  615. step: 7,
  616. source: 'background',
  617. payload: { code: result.code },
  618. });
  619. } else {
  620. throw new Error('Auth page tab was closed. Cannot fill verification code.');
  621. }
  622. }
  623. }
  624. // ============================================================
  625. // Step 8: Complete OAuth (webNavigation listener + chatgpt.js navigates)
  626. // ============================================================
  627. let webNavListener = null;
  628. async function executeStep8(state) {
  629. if (!state.oauthUrl) {
  630. throw new Error('No OAuth URL. Complete step 1 first.');
  631. }
  632. await addLog('Step 8: Setting up localhost redirect listener...');
  633. // Register webNavigation listener (scoped to this step)
  634. return new Promise((resolve, reject) => {
  635. const timeout = setTimeout(() => {
  636. if (webNavListener) {
  637. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  638. webNavListener = null;
  639. }
  640. setStepStatus(8, 'failed');
  641. addLog('Step 8: Localhost redirect not captured after 30s. Check if OAuth authorization completed.', 'error');
  642. reject(new Error('Localhost redirect not captured after 30s. Check if OAuth authorization completed.'));
  643. }, 30000);
  644. webNavListener = (details) => {
  645. if (details.url.startsWith('http://localhost')) {
  646. console.log(LOG_PREFIX, `Captured localhost redirect: ${details.url}`);
  647. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  648. webNavListener = null;
  649. clearTimeout(timeout);
  650. setState({ localhostUrl: details.url }).then(() => {
  651. addLog(`Step 8: Captured localhost URL: ${details.url}`, 'ok');
  652. setStepStatus(8, 'completed');
  653. notifyStepComplete(8, { localhostUrl: details.url });
  654. chrome.runtime.sendMessage({
  655. type: 'DATA_UPDATED',
  656. payload: { localhostUrl: details.url },
  657. }).catch(() => {});
  658. resolve();
  659. });
  660. }
  661. };
  662. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  663. // After step 7, the auth page shows a consent screen ("使用 ChatGPT 登录到 Codex")
  664. // with a "继续" button. We need to click it, which triggers the localhost redirect.
  665. (async () => {
  666. try {
  667. const signupTabId = await getTabId('signup-page');
  668. if (signupTabId) {
  669. await chrome.tabs.update(signupTabId, { active: true });
  670. await addLog('Step 8: Switching to auth page, clicking "继续" to complete OAuth...');
  671. await sendToContentScript('signup-page', {
  672. type: 'EXECUTE_STEP',
  673. step: 8,
  674. source: 'background',
  675. payload: {},
  676. });
  677. } else {
  678. // Auth tab was closed, reopen OAuth URL
  679. await chrome.tabs.create({ url: state.oauthUrl, active: true });
  680. await addLog('Step 8: Auth tab closed, reopening OAuth URL...');
  681. await sendToContentScript('signup-page', {
  682. type: 'EXECUTE_STEP',
  683. step: 8,
  684. source: 'background',
  685. payload: {},
  686. });
  687. }
  688. } catch (err) {
  689. clearTimeout(timeout);
  690. if (webNavListener) {
  691. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  692. webNavListener = null;
  693. }
  694. reject(err);
  695. }
  696. })();
  697. });
  698. }
  699. // ============================================================
  700. // Step 9: VPS Verify (via vps-panel.js)
  701. // ============================================================
  702. async function executeStep9(state) {
  703. if (!state.localhostUrl) {
  704. throw new Error('No localhost URL. Complete step 8 first.');
  705. }
  706. const vpsUrl = state.vpsUrl || 'http://154.26.182.181:8317/management.html#/oauth';
  707. // Switch to VPS panel tab
  708. const alive = await isTabAlive('vps-panel');
  709. if (!alive) {
  710. await addLog('Step 9: Opening VPS panel...');
  711. const tab = await chrome.tabs.create({ url: vpsUrl, active: true });
  712. await new Promise(resolve => {
  713. const listener = (tabId, info) => {
  714. if (tabId === tab.id && info.status === 'complete') {
  715. chrome.tabs.onUpdated.removeListener(listener);
  716. resolve();
  717. }
  718. };
  719. chrome.tabs.onUpdated.addListener(listener);
  720. });
  721. await chrome.scripting.executeScript({
  722. target: { tabId: tab.id },
  723. files: ['content/utils.js', 'content/vps-panel.js'],
  724. });
  725. } else {
  726. const tabId = await getTabId('vps-panel');
  727. if (tabId) await chrome.tabs.update(tabId, { active: true });
  728. }
  729. await sendToContentScript('vps-panel', {
  730. type: 'EXECUTE_STEP',
  731. step: 9,
  732. source: 'background',
  733. payload: {},
  734. });
  735. }
  736. // ============================================================
  737. // Open Side Panel on extension icon click
  738. // ============================================================
  739. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });