background.js 25 KB

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