background.js 37 KB

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