background.js 29 KB

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