background.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. // background.js — Service Worker: orchestration, state, tab management, message routing
  2. importScripts('data/names.js');
  3. const LOG_PREFIX = '[MultiPage:bg]';
  4. const DUCK_AUTOFILL_URL = 'https://duckduckgo.com/email/settings/autofill';
  5. const STOP_ERROR_MESSAGE = 'Flow stopped by user.';
  6. const HUMAN_STEP_DELAY_MIN = 700;
  7. const HUMAN_STEP_DELAY_MAX = 2200;
  8. initializeSessionStorageAccess();
  9. // ============================================================
  10. // State Management (chrome.storage.session)
  11. // ============================================================
  12. const DEFAULT_STATE = {
  13. currentStep: 0,
  14. stepStatuses: {
  15. 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending',
  16. 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
  17. },
  18. oauthUrl: null,
  19. email: null,
  20. password: null,
  21. accounts: [], // { email, password, createdAt }
  22. lastEmailTimestamp: null,
  23. localhostUrl: null,
  24. flowStartTime: null,
  25. tabRegistry: {},
  26. logs: [],
  27. vpsUrl: '',
  28. customPassword: '',
  29. mailProvider: '163', // 'qq' or '163'
  30. inbucketMailbox: '',
  31. };
  32. async function getState() {
  33. const state = await chrome.storage.session.get(null);
  34. return { ...DEFAULT_STATE, ...state };
  35. }
  36. async function initializeSessionStorageAccess() {
  37. try {
  38. if (chrome.storage?.session?.setAccessLevel) {
  39. await chrome.storage.session.setAccessLevel({
  40. accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS',
  41. });
  42. console.log(LOG_PREFIX, 'Enabled storage.session for content scripts');
  43. }
  44. } catch (err) {
  45. console.warn(LOG_PREFIX, 'Failed to enable storage.session for content scripts:', err?.message || err);
  46. }
  47. }
  48. async function setState(updates) {
  49. console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
  50. await chrome.storage.session.set(updates);
  51. }
  52. function broadcastDataUpdate(payload) {
  53. chrome.runtime.sendMessage({
  54. type: 'DATA_UPDATED',
  55. payload,
  56. }).catch(() => {});
  57. }
  58. async function setEmailState(email) {
  59. await setState({ email });
  60. broadcastDataUpdate({ email });
  61. }
  62. async function setPasswordState(password) {
  63. await setState({ password });
  64. broadcastDataUpdate({ password });
  65. }
  66. async function resetState() {
  67. console.log(LOG_PREFIX, 'Resetting all state');
  68. // Preserve settings and persistent data across resets
  69. const prev = await chrome.storage.session.get([
  70. 'seenCodes',
  71. 'seenInbucketMailIds',
  72. 'accounts',
  73. 'tabRegistry',
  74. 'vpsUrl',
  75. 'customPassword',
  76. 'mailProvider',
  77. 'inbucketMailbox',
  78. ]);
  79. await chrome.storage.session.clear();
  80. await chrome.storage.session.set({
  81. ...DEFAULT_STATE,
  82. seenCodes: prev.seenCodes || [],
  83. seenInbucketMailIds: prev.seenInbucketMailIds || [],
  84. accounts: prev.accounts || [],
  85. tabRegistry: prev.tabRegistry || {},
  86. vpsUrl: prev.vpsUrl || '',
  87. customPassword: prev.customPassword || '',
  88. mailProvider: prev.mailProvider || '163',
  89. inbucketMailbox: prev.inbucketMailbox || '',
  90. });
  91. }
  92. /**
  93. * Generate a random password: 14 chars, mix of uppercase, lowercase, digits, symbols.
  94. */
  95. function generatePassword() {
  96. const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  97. const lower = 'abcdefghjkmnpqrstuvwxyz';
  98. const digits = '23456789';
  99. const symbols = '!@#$%&*?';
  100. const all = upper + lower + digits + symbols;
  101. // Ensure at least one of each type
  102. let pw = '';
  103. pw += upper[Math.floor(Math.random() * upper.length)];
  104. pw += lower[Math.floor(Math.random() * lower.length)];
  105. pw += digits[Math.floor(Math.random() * digits.length)];
  106. pw += symbols[Math.floor(Math.random() * symbols.length)];
  107. // Fill remaining 10 chars
  108. for (let i = 0; i < 10; i++) {
  109. pw += all[Math.floor(Math.random() * all.length)];
  110. }
  111. // Shuffle
  112. return pw.split('').sort(() => Math.random() - 0.5).join('');
  113. }
  114. // ============================================================
  115. // Tab Registry
  116. // ============================================================
  117. async function getTabRegistry() {
  118. const state = await getState();
  119. return state.tabRegistry || {};
  120. }
  121. async function registerTab(source, tabId) {
  122. const registry = await getTabRegistry();
  123. registry[source] = { tabId, ready: true };
  124. await setState({ tabRegistry: registry });
  125. console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
  126. }
  127. async function isTabAlive(source) {
  128. const registry = await getTabRegistry();
  129. const entry = registry[source];
  130. if (!entry) return false;
  131. try {
  132. await chrome.tabs.get(entry.tabId);
  133. return true;
  134. } catch {
  135. // Tab no longer exists — clean up registry
  136. registry[source] = null;
  137. await setState({ tabRegistry: registry });
  138. return false;
  139. }
  140. }
  141. async function getTabId(source) {
  142. const registry = await getTabRegistry();
  143. return registry[source]?.tabId || null;
  144. }
  145. // ============================================================
  146. // Command Queue (for content scripts not yet ready)
  147. // ============================================================
  148. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  149. function queueCommand(source, message, timeout = 15000) {
  150. return new Promise((resolve, reject) => {
  151. const timer = setTimeout(() => {
  152. pendingCommands.delete(source);
  153. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  154. console.error(LOG_PREFIX, err);
  155. reject(new Error(err));
  156. }, timeout);
  157. pendingCommands.set(source, { message, resolve, reject, timer });
  158. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  159. });
  160. }
  161. function flushCommand(source, tabId) {
  162. const pending = pendingCommands.get(source);
  163. if (pending) {
  164. clearTimeout(pending.timer);
  165. pendingCommands.delete(source);
  166. chrome.tabs.sendMessage(tabId, pending.message).then(pending.resolve).catch(pending.reject);
  167. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  168. }
  169. }
  170. function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
  171. for (const [source, pending] of pendingCommands.entries()) {
  172. clearTimeout(pending.timer);
  173. pending.reject(new Error(reason));
  174. pendingCommands.delete(source);
  175. console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
  176. }
  177. }
  178. // ============================================================
  179. // Reuse or create tab
  180. // ============================================================
  181. async function reuseOrCreateTab(source, url, options = {}) {
  182. const alive = await isTabAlive(source);
  183. if (alive) {
  184. const tabId = await getTabId(source);
  185. const currentTab = await chrome.tabs.get(tabId);
  186. const sameUrl = currentTab.url === url;
  187. const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
  188. const registry = await getTabRegistry();
  189. if (sameUrl) {
  190. await chrome.tabs.update(tabId, { active: true });
  191. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
  192. if (shouldReloadOnReuse) {
  193. if (registry[source]) registry[source].ready = false;
  194. await setState({ tabRegistry: registry });
  195. await chrome.tabs.reload(tabId);
  196. await new Promise((resolve) => {
  197. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  198. const listener = (tid, info) => {
  199. if (tid === tabId && info.status === 'complete') {
  200. chrome.tabs.onUpdated.removeListener(listener);
  201. clearTimeout(timer);
  202. resolve();
  203. }
  204. };
  205. chrome.tabs.onUpdated.addListener(listener);
  206. });
  207. }
  208. // For dynamically injected pages like the VPS panel, re-inject immediately.
  209. if (options.inject) {
  210. if (registry[source]) registry[source].ready = false;
  211. await setState({ tabRegistry: registry });
  212. await chrome.scripting.executeScript({
  213. target: { tabId },
  214. files: options.inject,
  215. });
  216. await new Promise(r => setTimeout(r, 500));
  217. }
  218. return tabId;
  219. }
  220. // Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
  221. if (registry[source]) registry[source].ready = false;
  222. await setState({ tabRegistry: registry });
  223. // Navigate existing tab to new URL
  224. await chrome.tabs.update(tabId, { url, active: true });
  225. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
  226. // Wait for page load complete (with 30s timeout)
  227. await new Promise((resolve) => {
  228. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  229. const listener = (tid, info) => {
  230. if (tid === tabId && info.status === 'complete') {
  231. chrome.tabs.onUpdated.removeListener(listener);
  232. clearTimeout(timer);
  233. resolve();
  234. }
  235. };
  236. chrome.tabs.onUpdated.addListener(listener);
  237. });
  238. // If dynamic injection needed (VPS panel), re-inject after navigation
  239. if (options.inject) {
  240. await chrome.scripting.executeScript({
  241. target: { tabId },
  242. files: options.inject,
  243. });
  244. }
  245. // Wait a bit for content script to inject and send READY
  246. await new Promise(r => setTimeout(r, 500));
  247. return tabId;
  248. }
  249. // Create new tab
  250. const tab = await chrome.tabs.create({ url, active: true });
  251. console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
  252. // If dynamic injection needed (VPS panel), inject scripts after load
  253. if (options.inject) {
  254. await new Promise((resolve) => {
  255. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  256. const listener = (tabId, info) => {
  257. if (tabId === tab.id && info.status === 'complete') {
  258. chrome.tabs.onUpdated.removeListener(listener);
  259. clearTimeout(timer);
  260. resolve();
  261. }
  262. };
  263. chrome.tabs.onUpdated.addListener(listener);
  264. });
  265. await chrome.scripting.executeScript({
  266. target: { tabId: tab.id },
  267. files: options.inject,
  268. });
  269. }
  270. return tab.id;
  271. }
  272. // ============================================================
  273. // Send command to content script (with readiness check)
  274. // ============================================================
  275. async function sendToContentScript(source, message) {
  276. const registry = await getTabRegistry();
  277. const entry = registry[source];
  278. if (!entry || !entry.ready) {
  279. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  280. return queueCommand(source, message);
  281. }
  282. // Verify tab is still alive
  283. const alive = await isTabAlive(source);
  284. if (!alive) {
  285. // Tab was closed — queue the command, it will be sent when tab is reopened
  286. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  287. return queueCommand(source, message);
  288. }
  289. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  290. return chrome.tabs.sendMessage(entry.tabId, message);
  291. }
  292. // ============================================================
  293. // Logging
  294. // ============================================================
  295. async function addLog(message, level = 'info') {
  296. const state = await getState();
  297. const logs = state.logs || [];
  298. const entry = { message, level, timestamp: Date.now() };
  299. logs.push(entry);
  300. // Keep last 500 logs
  301. if (logs.length > 500) logs.splice(0, logs.length - 500);
  302. await setState({ logs });
  303. // Broadcast to side panel
  304. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => {});
  305. }
  306. // ============================================================
  307. // Step Status Management
  308. // ============================================================
  309. async function setStepStatus(step, status) {
  310. const state = await getState();
  311. const statuses = { ...state.stepStatuses };
  312. statuses[step] = status;
  313. await setState({ stepStatuses: statuses, currentStep: step });
  314. // Broadcast to side panel
  315. chrome.runtime.sendMessage({
  316. type: 'STEP_STATUS_CHANGED',
  317. payload: { step, status },
  318. }).catch(() => {});
  319. }
  320. function isStopError(error) {
  321. const message = typeof error === 'string' ? error : error?.message;
  322. return message === STOP_ERROR_MESSAGE;
  323. }
  324. function clearStopRequest() {
  325. stopRequested = false;
  326. }
  327. function throwIfStopped() {
  328. if (stopRequested) {
  329. throw new Error(STOP_ERROR_MESSAGE);
  330. }
  331. }
  332. async function sleepWithStop(ms) {
  333. const start = Date.now();
  334. while (Date.now() - start < ms) {
  335. throwIfStopped();
  336. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  337. }
  338. }
  339. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  340. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  341. await sleepWithStop(duration);
  342. }
  343. async function clickWithDebugger(tabId, rect) {
  344. if (!tabId) {
  345. throw new Error('No auth tab found for debugger click.');
  346. }
  347. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  348. throw new Error('Step 8 debugger fallback needs a valid button position.');
  349. }
  350. const target = { tabId };
  351. try {
  352. await chrome.debugger.attach(target, '1.3');
  353. } catch (err) {
  354. throw new Error(
  355. `Debugger attach failed during step 8 fallback: ${err.message}. ` +
  356. 'If DevTools is open on the auth tab, close it and retry.'
  357. );
  358. }
  359. try {
  360. const x = Math.round(rect.centerX);
  361. const y = Math.round(rect.centerY);
  362. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  363. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  364. type: 'mouseMoved',
  365. x,
  366. y,
  367. button: 'none',
  368. buttons: 0,
  369. clickCount: 0,
  370. });
  371. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  372. type: 'mousePressed',
  373. x,
  374. y,
  375. button: 'left',
  376. buttons: 1,
  377. clickCount: 1,
  378. });
  379. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  380. type: 'mouseReleased',
  381. x,
  382. y,
  383. button: 'left',
  384. buttons: 0,
  385. clickCount: 1,
  386. });
  387. } finally {
  388. await chrome.debugger.detach(target).catch(() => {});
  389. }
  390. }
  391. async function broadcastStopToContentScripts() {
  392. const registry = await getTabRegistry();
  393. for (const entry of Object.values(registry)) {
  394. if (!entry?.tabId) continue;
  395. try {
  396. await chrome.tabs.sendMessage(entry.tabId, {
  397. type: 'STOP_FLOW',
  398. source: 'background',
  399. payload: {},
  400. });
  401. } catch {}
  402. }
  403. }
  404. let stopRequested = false;
  405. // ============================================================
  406. // Message Handler (central router)
  407. // ============================================================
  408. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  409. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  410. handleMessage(message, sender).then(response => {
  411. sendResponse(response);
  412. }).catch(err => {
  413. console.error(LOG_PREFIX, 'Handler error:', err);
  414. sendResponse({ error: err.message });
  415. });
  416. return true; // async response
  417. });
  418. async function handleMessage(message, sender) {
  419. switch (message.type) {
  420. case 'CONTENT_SCRIPT_READY': {
  421. const tabId = sender.tab?.id;
  422. if (tabId && message.source) {
  423. await registerTab(message.source, tabId);
  424. flushCommand(message.source, tabId);
  425. await addLog(`Content script ready: ${message.source} (tab ${tabId})`);
  426. }
  427. return { ok: true };
  428. }
  429. case 'LOG': {
  430. const { message: msg, level } = message.payload;
  431. await addLog(`[${message.source}] ${msg}`, level);
  432. return { ok: true };
  433. }
  434. case 'STEP_COMPLETE': {
  435. if (stopRequested) {
  436. await setStepStatus(message.step, 'stopped');
  437. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  438. return { ok: true };
  439. }
  440. await setStepStatus(message.step, 'completed');
  441. await addLog(`Step ${message.step} completed`, 'ok');
  442. await handleStepData(message.step, message.payload);
  443. notifyStepComplete(message.step, message.payload);
  444. return { ok: true };
  445. }
  446. case 'STEP_ERROR': {
  447. if (isStopError(message.error)) {
  448. await setStepStatus(message.step, 'stopped');
  449. await addLog(`Step ${message.step} stopped by user`, 'warn');
  450. notifyStepError(message.step, message.error);
  451. } else {
  452. await setStepStatus(message.step, 'failed');
  453. await addLog(`Step ${message.step} failed: ${message.error}`, 'error');
  454. notifyStepError(message.step, message.error);
  455. }
  456. return { ok: true };
  457. }
  458. case 'GET_STATE': {
  459. return await getState();
  460. }
  461. case 'RESET': {
  462. clearStopRequest();
  463. await resetState();
  464. await addLog('Flow reset', 'info');
  465. return { ok: true };
  466. }
  467. case 'EXECUTE_STEP': {
  468. clearStopRequest();
  469. const step = message.payload.step;
  470. // Save email if provided (from side panel step 3)
  471. if (message.payload.email) {
  472. await setEmailState(message.payload.email);
  473. }
  474. await executeStep(step);
  475. return { ok: true };
  476. }
  477. case 'AUTO_RUN': {
  478. clearStopRequest();
  479. const totalRuns = message.payload?.totalRuns || 1;
  480. autoRunLoop(totalRuns); // fire-and-forget
  481. return { ok: true };
  482. }
  483. case 'RESUME_AUTO_RUN': {
  484. clearStopRequest();
  485. if (message.payload.email) {
  486. await setEmailState(message.payload.email);
  487. }
  488. resumeAutoRun(); // fire-and-forget
  489. return { ok: true };
  490. }
  491. case 'SAVE_SETTING': {
  492. const updates = {};
  493. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  494. if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
  495. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  496. if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
  497. await setState(updates);
  498. return { ok: true };
  499. }
  500. // Side panel data updates
  501. case 'SAVE_EMAIL': {
  502. await setEmailState(message.payload.email);
  503. return { ok: true, email: message.payload.email };
  504. }
  505. case 'FETCH_DUCK_EMAIL': {
  506. clearStopRequest();
  507. const email = await fetchDuckEmail(message.payload || {});
  508. return { ok: true, email };
  509. }
  510. case 'STOP_FLOW': {
  511. await requestStop();
  512. return { ok: true };
  513. }
  514. default:
  515. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  516. return { error: `Unknown message type: ${message.type}` };
  517. }
  518. }
  519. // ============================================================
  520. // Step Data Handlers
  521. // ============================================================
  522. async function handleStepData(step, payload) {
  523. switch (step) {
  524. case 1:
  525. if (payload.oauthUrl) {
  526. await setState({ oauthUrl: payload.oauthUrl });
  527. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  528. }
  529. break;
  530. case 3:
  531. if (payload.email) await setEmailState(payload.email);
  532. break;
  533. case 4:
  534. if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
  535. break;
  536. case 8:
  537. if (payload.localhostUrl) {
  538. await setState({ localhostUrl: payload.localhostUrl });
  539. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  540. }
  541. break;
  542. }
  543. }
  544. // ============================================================
  545. // Step Completion Waiting
  546. // ============================================================
  547. // Map of step -> { resolve, reject } for waiting on step completion
  548. const stepWaiters = new Map();
  549. let resumeWaiter = null;
  550. function waitForStepComplete(step, timeoutMs = 120000) {
  551. return new Promise((resolve, reject) => {
  552. throwIfStopped();
  553. const timer = setTimeout(() => {
  554. stepWaiters.delete(step);
  555. reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
  556. }, timeoutMs);
  557. stepWaiters.set(step, {
  558. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  559. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  560. });
  561. });
  562. }
  563. function notifyStepComplete(step, payload) {
  564. const waiter = stepWaiters.get(step);
  565. if (waiter) waiter.resolve(payload);
  566. }
  567. function notifyStepError(step, error) {
  568. const waiter = stepWaiters.get(step);
  569. if (waiter) waiter.reject(new Error(error));
  570. }
  571. async function markRunningStepsStopped() {
  572. const state = await getState();
  573. const runningSteps = Object.entries(state.stepStatuses || {})
  574. .filter(([, status]) => status === 'running')
  575. .map(([step]) => Number(step));
  576. for (const step of runningSteps) {
  577. await setStepStatus(step, 'stopped');
  578. }
  579. }
  580. async function requestStop() {
  581. if (stopRequested) return;
  582. stopRequested = true;
  583. cancelPendingCommands();
  584. if (webNavListener) {
  585. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  586. webNavListener = null;
  587. }
  588. await addLog('Stop requested. Cancelling current operations...', 'warn');
  589. await broadcastStopToContentScripts();
  590. for (const waiter of stepWaiters.values()) {
  591. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  592. }
  593. stepWaiters.clear();
  594. if (resumeWaiter) {
  595. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  596. resumeWaiter = null;
  597. }
  598. await markRunningStepsStopped();
  599. autoRunActive = false;
  600. await setState({ autoRunning: false });
  601. chrome.runtime.sendMessage({
  602. type: 'AUTO_RUN_STATUS',
  603. payload: { phase: 'stopped', currentRun: autoRunCurrentRun, totalRuns: autoRunTotalRuns },
  604. }).catch(() => {});
  605. }
  606. // ============================================================
  607. // Step Execution
  608. // ============================================================
  609. async function executeStep(step) {
  610. console.log(LOG_PREFIX, `Executing step ${step}`);
  611. throwIfStopped();
  612. await setStepStatus(step, 'running');
  613. await addLog(`Step ${step} started`);
  614. await humanStepDelay();
  615. const state = await getState();
  616. // Set flow start time on first step
  617. if (step === 1 && !state.flowStartTime) {
  618. await setState({ flowStartTime: Date.now() });
  619. }
  620. try {
  621. switch (step) {
  622. case 1: await executeStep1(state); break;
  623. case 2: await executeStep2(state); break;
  624. case 3: await executeStep3(state); break;
  625. case 4: await executeStep4(state); break;
  626. case 5: await executeStep5(state); break;
  627. case 6: await executeStep6(state); break;
  628. case 7: await executeStep7(state); break;
  629. case 8: await executeStep8(state); break;
  630. case 9: await executeStep9(state); break;
  631. default:
  632. throw new Error(`Unknown step: ${step}`);
  633. }
  634. } catch (err) {
  635. if (isStopError(err)) {
  636. await setStepStatus(step, 'stopped');
  637. await addLog(`Step ${step} stopped by user`, 'warn');
  638. throw err;
  639. }
  640. await setStepStatus(step, 'failed');
  641. await addLog(`Step ${step} failed: ${err.message}`, 'error');
  642. throw err;
  643. }
  644. }
  645. /**
  646. * Execute a step and wait for it to complete before returning.
  647. * @param {number} step
  648. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  649. */
  650. async function executeStepAndWait(step, delayAfter = 2000) {
  651. throwIfStopped();
  652. const promise = waitForStepComplete(step, 120000);
  653. await executeStep(step);
  654. await promise;
  655. // Extra delay for page transitions / DOM updates
  656. if (delayAfter > 0) {
  657. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  658. }
  659. }
  660. async function fetchDuckEmail(options = {}) {
  661. throwIfStopped();
  662. const { generateNew = true } = options;
  663. await addLog(`Duck Mail: Opening autofill settings (${generateNew ? 'generate new' : 'reuse current'})...`);
  664. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  665. const result = await sendToContentScript('duck-mail', {
  666. type: 'FETCH_DUCK_EMAIL',
  667. source: 'background',
  668. payload: { generateNew },
  669. });
  670. if (result?.error) {
  671. throw new Error(result.error);
  672. }
  673. if (!result?.email) {
  674. throw new Error('Duck email not returned.');
  675. }
  676. await setEmailState(result.email);
  677. await addLog(`Duck Mail: ${result.generated ? 'Generated' : 'Loaded'} ${result.email}`, 'ok');
  678. return result.email;
  679. }
  680. // ============================================================
  681. // Auto Run Flow
  682. // ============================================================
  683. let autoRunActive = false;
  684. let autoRunCurrentRun = 0;
  685. let autoRunTotalRuns = 1;
  686. // Outer loop: runs the full flow N times
  687. async function autoRunLoop(totalRuns) {
  688. if (autoRunActive) {
  689. await addLog('Auto run already in progress', 'warn');
  690. return;
  691. }
  692. clearStopRequest();
  693. autoRunActive = true;
  694. autoRunTotalRuns = totalRuns;
  695. await setState({ autoRunning: true });
  696. for (let run = 1; run <= totalRuns; run++) {
  697. autoRunCurrentRun = run;
  698. // Reset everything at the start of each run (keep VPS/mail settings)
  699. const prevState = await getState();
  700. const keepSettings = {
  701. vpsUrl: prevState.vpsUrl,
  702. mailProvider: prevState.mailProvider,
  703. inbucketMailbox: prevState.inbucketMailbox,
  704. autoRunning: true,
  705. };
  706. await resetState();
  707. await setState(keepSettings);
  708. // Tell side panel to reset all UI
  709. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => {});
  710. await sleepWithStop(500);
  711. await addLog(`=== Auto Run ${run}/${totalRuns} — Phase 1: Get OAuth link & open signup ===`, 'info');
  712. const status = (phase) => ({ type: 'AUTO_RUN_STATUS', payload: { phase, currentRun: run, totalRuns } });
  713. try {
  714. throwIfStopped();
  715. chrome.runtime.sendMessage(status('running')).catch(() => {});
  716. await executeStepAndWait(1, 2000);
  717. await executeStepAndWait(2, 2000);
  718. let emailReady = false;
  719. try {
  720. const duckEmail = await fetchDuckEmail({ generateNew: true });
  721. await addLog(`=== Run ${run}/${totalRuns} — Duck email ready: ${duckEmail} ===`, 'ok');
  722. emailReady = true;
  723. } catch (err) {
  724. await addLog(`Duck Mail auto-fetch failed: ${err.message}`, 'warn');
  725. }
  726. if (!emailReady) {
  727. await addLog(`=== Run ${run}/${totalRuns} PAUSED: Fetch Duck email or paste manually, then continue ===`, 'warn');
  728. chrome.runtime.sendMessage(status('waiting_email')).catch(() => {});
  729. // Wait for RESUME_AUTO_RUN — sets a promise that resumeAutoRun resolves
  730. await waitForResume();
  731. const resumedState = await getState();
  732. if (!resumedState.email) {
  733. await addLog('Cannot resume: no email address.', 'error');
  734. break;
  735. }
  736. }
  737. await addLog(`=== Run ${run}/${totalRuns} — Phase 2: Register, verify, login, complete ===`, 'info');
  738. chrome.runtime.sendMessage(status('running')).catch(() => {});
  739. const signupTabId = await getTabId('signup-page');
  740. if (signupTabId) {
  741. await chrome.tabs.update(signupTabId, { active: true });
  742. }
  743. await executeStepAndWait(3, 3000);
  744. await executeStepAndWait(4, 2000);
  745. await executeStepAndWait(5, 3000);
  746. await executeStepAndWait(6, 3000);
  747. await executeStepAndWait(7, 2000);
  748. await executeStepAndWait(8, 2000);
  749. await executeStepAndWait(9, 1000);
  750. await addLog(`=== Run ${run}/${totalRuns} COMPLETE! ===`, 'ok');
  751. } catch (err) {
  752. if (isStopError(err)) {
  753. await addLog(`Run ${run}/${totalRuns} stopped by user`, 'warn');
  754. } else {
  755. await addLog(`Run ${run}/${totalRuns} failed: ${err.message}`, 'error');
  756. }
  757. chrome.runtime.sendMessage(status('stopped')).catch(() => {});
  758. break; // Stop on error
  759. }
  760. }
  761. const completedRuns = autoRunCurrentRun;
  762. if (stopRequested) {
  763. await addLog(`=== Stopped after ${Math.max(0, completedRuns - 1)}/${autoRunTotalRuns} runs ===`, 'warn');
  764. chrome.runtime.sendMessage({ type: 'AUTO_RUN_STATUS', payload: { phase: 'stopped', currentRun: completedRuns, totalRuns: autoRunTotalRuns } }).catch(() => {});
  765. } else if (completedRuns >= autoRunTotalRuns) {
  766. await addLog(`=== All ${autoRunTotalRuns} runs completed successfully ===`, 'ok');
  767. chrome.runtime.sendMessage({ type: 'AUTO_RUN_STATUS', payload: { phase: 'complete', currentRun: completedRuns, totalRuns: autoRunTotalRuns } }).catch(() => {});
  768. } else {
  769. await addLog(`=== Stopped after ${completedRuns}/${autoRunTotalRuns} runs ===`, 'warn');
  770. chrome.runtime.sendMessage({ type: 'AUTO_RUN_STATUS', payload: { phase: 'stopped', currentRun: completedRuns, totalRuns: autoRunTotalRuns } }).catch(() => {});
  771. }
  772. autoRunActive = false;
  773. await setState({ autoRunning: false });
  774. clearStopRequest();
  775. }
  776. function waitForResume() {
  777. return new Promise((resolve, reject) => {
  778. throwIfStopped();
  779. resumeWaiter = { resolve, reject };
  780. });
  781. }
  782. async function resumeAutoRun() {
  783. throwIfStopped();
  784. const state = await getState();
  785. if (!state.email) {
  786. await addLog('Cannot resume: no email address. Paste email in Side Panel first.', 'error');
  787. return;
  788. }
  789. if (resumeWaiter) {
  790. resumeWaiter.resolve();
  791. resumeWaiter = null;
  792. }
  793. }
  794. // ============================================================
  795. // Step 1: Get OAuth Link (via vps-panel.js)
  796. // ============================================================
  797. async function executeStep1(state) {
  798. if (!state.vpsUrl) {
  799. throw new Error('No VPS URL configured. Enter VPS address in Side Panel first.');
  800. }
  801. await addLog(`Step 1: Opening VPS panel...`);
  802. await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  803. inject: ['content/utils.js', 'content/vps-panel.js'],
  804. reloadIfSameUrl: true,
  805. });
  806. await sendToContentScript('vps-panel', {
  807. type: 'EXECUTE_STEP',
  808. step: 1,
  809. source: 'background',
  810. payload: {},
  811. });
  812. }
  813. // ============================================================
  814. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  815. // ============================================================
  816. async function executeStep2(state) {
  817. if (!state.oauthUrl) {
  818. throw new Error('No OAuth URL. Complete step 1 first.');
  819. }
  820. await addLog(`Step 2: Opening auth URL...`);
  821. await reuseOrCreateTab('signup-page', state.oauthUrl);
  822. await sendToContentScript('signup-page', {
  823. type: 'EXECUTE_STEP',
  824. step: 2,
  825. source: 'background',
  826. payload: {},
  827. });
  828. }
  829. // ============================================================
  830. // Step 3: Fill Email & Password (via signup-page.js)
  831. // ============================================================
  832. async function executeStep3(state) {
  833. if (!state.email) {
  834. throw new Error('No email address. Paste email in Side Panel first.');
  835. }
  836. const password = state.customPassword || generatePassword();
  837. await setPasswordState(password);
  838. // Save account record
  839. const accounts = state.accounts || [];
  840. accounts.push({ email: state.email, password, createdAt: new Date().toISOString() });
  841. await setState({ accounts });
  842. await addLog(
  843. `Step 3: Filling email ${state.email}, password ${state.customPassword ? 'customized' : 'generated'} (${password.length} chars)`
  844. );
  845. await sendToContentScript('signup-page', {
  846. type: 'EXECUTE_STEP',
  847. step: 3,
  848. source: 'background',
  849. payload: { email: state.email, password },
  850. });
  851. }
  852. // ============================================================
  853. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  854. // ============================================================
  855. function getMailConfig(state) {
  856. const provider = state.mailProvider || 'qq';
  857. if (provider === '163') {
  858. 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' };
  859. }
  860. if (provider === 'inbucket') {
  861. const mailbox = (state.inbucketMailbox || '').trim();
  862. if (!mailbox) {
  863. return { error: 'Inbucket mailbox name is empty.' };
  864. }
  865. return {
  866. source: 'inbucket-mail',
  867. url: `https://inbucket.j2to.de/m/${encodeURIComponent(mailbox)}/`,
  868. label: `Inbucket Mailbox (${mailbox})`,
  869. navigateOnReuse: true,
  870. };
  871. }
  872. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ Mail' };
  873. }
  874. async function executeStep4(state) {
  875. const mail = getMailConfig(state);
  876. if (mail.error) throw new Error(mail.error);
  877. await addLog(`Step 4: Opening ${mail.label}...`);
  878. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  879. const alive = await isTabAlive(mail.source);
  880. if (alive) {
  881. if (mail.navigateOnReuse) {
  882. await reuseOrCreateTab(mail.source, mail.url);
  883. } else {
  884. const tabId = await getTabId(mail.source);
  885. await chrome.tabs.update(tabId, { active: true });
  886. }
  887. } else {
  888. await reuseOrCreateTab(mail.source, mail.url);
  889. }
  890. const result = await sendToContentScript(mail.source, {
  891. type: 'POLL_EMAIL',
  892. step: 4,
  893. source: 'background',
  894. payload: {
  895. filterAfterTimestamp: state.flowStartTime || 0,
  896. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  897. subjectFilters: ['verify', 'verification', 'code', '验证', 'confirm'],
  898. targetEmail: state.email,
  899. maxAttempts: 20,
  900. intervalMs: 3000,
  901. },
  902. });
  903. if (result && result.error) {
  904. throw new Error(result.error);
  905. }
  906. if (result && result.code) {
  907. await setState({ lastEmailTimestamp: result.emailTimestamp });
  908. await addLog(`Step 4: Got verification code: ${result.code}`);
  909. // Switch to signup tab and fill code
  910. const signupTabId = await getTabId('signup-page');
  911. if (signupTabId) {
  912. await chrome.tabs.update(signupTabId, { active: true });
  913. await sendToContentScript('signup-page', {
  914. type: 'FILL_CODE',
  915. step: 4,
  916. source: 'background',
  917. payload: { code: result.code },
  918. });
  919. } else {
  920. throw new Error('Signup page tab was closed. Cannot fill verification code.');
  921. }
  922. }
  923. }
  924. // ============================================================
  925. // Step 5: Fill Name & Birthday (via signup-page.js)
  926. // ============================================================
  927. async function executeStep5(state) {
  928. const { firstName, lastName } = generateRandomName();
  929. const { year, month, day } = generateRandomBirthday();
  930. await addLog(`Step 5: Generated name: ${firstName} ${lastName}, Birthday: ${year}-${month}-${day}`);
  931. await sendToContentScript('signup-page', {
  932. type: 'EXECUTE_STEP',
  933. step: 5,
  934. source: 'background',
  935. payload: { firstName, lastName, year, month, day },
  936. });
  937. }
  938. // ============================================================
  939. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  940. // ============================================================
  941. async function executeStep6(state) {
  942. if (!state.oauthUrl) {
  943. throw new Error('No OAuth URL. Complete step 1 first.');
  944. }
  945. if (!state.email) {
  946. throw new Error('No email. Complete step 3 first.');
  947. }
  948. await addLog(`Step 6: Opening OAuth URL for login...`);
  949. // Reuse the signup-page tab — navigate it to the OAuth URL
  950. await reuseOrCreateTab('signup-page', state.oauthUrl);
  951. // signup-page.js will inject (same auth.openai.com domain) and handle login
  952. await sendToContentScript('signup-page', {
  953. type: 'EXECUTE_STEP',
  954. step: 6,
  955. source: 'background',
  956. payload: { email: state.email, password: state.password },
  957. });
  958. }
  959. // ============================================================
  960. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  961. // ============================================================
  962. async function executeStep7(state) {
  963. const mail = getMailConfig(state);
  964. if (mail.error) throw new Error(mail.error);
  965. await addLog(`Step 7: Opening ${mail.label}...`);
  966. const alive = await isTabAlive(mail.source);
  967. if (alive) {
  968. if (mail.navigateOnReuse) {
  969. await reuseOrCreateTab(mail.source, mail.url);
  970. } else {
  971. const tabId = await getTabId(mail.source);
  972. await chrome.tabs.update(tabId, { active: true });
  973. }
  974. } else {
  975. await reuseOrCreateTab(mail.source, mail.url);
  976. }
  977. const result = await sendToContentScript(mail.source, {
  978. type: 'POLL_EMAIL',
  979. step: 7,
  980. source: 'background',
  981. payload: {
  982. filterAfterTimestamp: state.lastEmailTimestamp || state.flowStartTime || 0,
  983. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  984. subjectFilters: ['verify', 'verification', 'code', '验证', 'confirm', 'login'],
  985. targetEmail: state.email,
  986. maxAttempts: 20,
  987. intervalMs: 3000,
  988. },
  989. });
  990. if (result && result.error) {
  991. throw new Error(result.error);
  992. }
  993. if (result && result.code) {
  994. await addLog(`Step 7: Got login verification code: ${result.code}`);
  995. // Switch to signup/auth tab and fill code
  996. const signupTabId = await getTabId('signup-page');
  997. if (signupTabId) {
  998. await chrome.tabs.update(signupTabId, { active: true });
  999. await sendToContentScript('signup-page', {
  1000. type: 'FILL_CODE',
  1001. step: 7,
  1002. source: 'background',
  1003. payload: { code: result.code },
  1004. });
  1005. } else {
  1006. throw new Error('Auth page tab was closed. Cannot fill verification code.');
  1007. }
  1008. }
  1009. }
  1010. // ============================================================
  1011. // Step 8: Complete OAuth (auto click + localhost listener)
  1012. // ============================================================
  1013. let webNavListener = null;
  1014. async function executeStep8(state) {
  1015. if (!state.oauthUrl) {
  1016. throw new Error('No OAuth URL. Complete step 1 first.');
  1017. }
  1018. await addLog('Step 8: Setting up localhost redirect listener...');
  1019. // Register webNavigation listener (scoped to this step)
  1020. return new Promise((resolve, reject) => {
  1021. let resolved = false;
  1022. let resolveCaptureWait = null;
  1023. const captureWait = new Promise((resolveCapture) => {
  1024. resolveCaptureWait = resolveCapture;
  1025. });
  1026. const cleanupListener = () => {
  1027. if (webNavListener) {
  1028. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  1029. webNavListener = null;
  1030. }
  1031. };
  1032. const timeout = setTimeout(() => {
  1033. cleanupListener();
  1034. reject(new Error('Localhost redirect not captured after 120s. Step 8 click may have been blocked.'));
  1035. }, 120000);
  1036. webNavListener = (details) => {
  1037. if (details.url.startsWith('http://localhost')) {
  1038. console.log(LOG_PREFIX, `Captured localhost redirect: ${details.url}`);
  1039. resolved = true;
  1040. cleanupListener();
  1041. clearTimeout(timeout);
  1042. if (resolveCaptureWait) resolveCaptureWait(details.url);
  1043. setState({ localhostUrl: details.url }).then(() => {
  1044. addLog(`Step 8: Captured localhost URL: ${details.url}`, 'ok');
  1045. setStepStatus(8, 'completed');
  1046. notifyStepComplete(8, { localhostUrl: details.url });
  1047. broadcastDataUpdate({ localhostUrl: details.url });
  1048. resolve();
  1049. });
  1050. }
  1051. };
  1052. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  1053. // After step 7, the auth page shows a consent screen ("使用 ChatGPT 登录到 Codex")
  1054. // with a "继续" button. We locate the button in-page, then click it through
  1055. // the debugger Input API directly.
  1056. (async () => {
  1057. try {
  1058. let signupTabId = await getTabId('signup-page');
  1059. if (signupTabId) {
  1060. await chrome.tabs.update(signupTabId, { active: true });
  1061. await addLog('Step 8: Switched to auth page. Preparing debugger click...');
  1062. } else {
  1063. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  1064. await addLog('Step 8: Auth tab reopened. Preparing debugger click...');
  1065. }
  1066. const clickResult = await sendToContentScript('signup-page', {
  1067. type: 'STEP8_FIND_AND_CLICK',
  1068. source: 'background',
  1069. payload: {},
  1070. });
  1071. if (clickResult?.error) {
  1072. throw new Error(clickResult.error);
  1073. }
  1074. if (!resolved) {
  1075. await clickWithDebugger(signupTabId, clickResult?.rect);
  1076. await addLog('Step 8: Debugger click dispatched, waiting for redirect...');
  1077. }
  1078. } catch (err) {
  1079. clearTimeout(timeout);
  1080. cleanupListener();
  1081. reject(err);
  1082. }
  1083. })();
  1084. });
  1085. }
  1086. // ============================================================
  1087. // Step 9: VPS Verify (via vps-panel.js)
  1088. // ============================================================
  1089. async function executeStep9(state) {
  1090. if (!state.localhostUrl) {
  1091. throw new Error('No localhost URL. Complete step 8 first.');
  1092. }
  1093. if (!state.vpsUrl) {
  1094. throw new Error('VPS URL not set. Please enter VPS URL in the side panel.');
  1095. }
  1096. await addLog('Step 9: Opening VPS panel...');
  1097. let tabId = await getTabId('vps-panel');
  1098. const alive = tabId && await isTabAlive('vps-panel');
  1099. if (!alive) {
  1100. // Create new tab
  1101. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  1102. tabId = tab.id;
  1103. await new Promise(resolve => {
  1104. const listener = (tid, info) => {
  1105. if (tid === tabId && info.status === 'complete') {
  1106. chrome.tabs.onUpdated.removeListener(listener);
  1107. resolve();
  1108. }
  1109. };
  1110. chrome.tabs.onUpdated.addListener(listener);
  1111. });
  1112. } else {
  1113. await chrome.tabs.update(tabId, { active: true });
  1114. }
  1115. // Inject scripts directly and wait for them to be ready
  1116. await chrome.scripting.executeScript({
  1117. target: { tabId },
  1118. files: ['content/utils.js', 'content/vps-panel.js'],
  1119. });
  1120. await new Promise(r => setTimeout(r, 1000));
  1121. // Send command directly — bypass queue/ready mechanism
  1122. await addLog(`Step 9: Filling callback URL...`);
  1123. await chrome.tabs.sendMessage(tabId, {
  1124. type: 'EXECUTE_STEP',
  1125. step: 9,
  1126. source: 'background',
  1127. payload: { localhostUrl: state.localhostUrl },
  1128. });
  1129. }
  1130. // ============================================================
  1131. // Open Side Panel on extension icon click
  1132. // ============================================================
  1133. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });