background.js 29 KB

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