background.js 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896
  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 = '流程已被用户停止。';
  6. const HUMAN_STEP_DELAY_MIN = 700;
  7. const HUMAN_STEP_DELAY_MAX = 2200;
  8. initializeSessionStorageAccess();
  9. // ============================================================
  10. // State Management (chrome.storage.session + chrome.storage.local)
  11. // ============================================================
  12. const PERSISTED_SETTING_DEFAULTS = {
  13. vpsUrl: '',
  14. vpsPassword: '',
  15. customPassword: '',
  16. autoRunSkipFailures: false,
  17. mailProvider: '163',
  18. inbucketHost: '',
  19. inbucketMailbox: '',
  20. };
  21. const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);
  22. const DEFAULT_STATE = {
  23. currentStep: 0,
  24. stepStatuses: {
  25. 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending',
  26. 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
  27. },
  28. oauthUrl: null,
  29. email: null,
  30. password: null,
  31. accounts: [], // { email, password, createdAt }
  32. lastEmailTimestamp: null,
  33. lastSignupCode: null,
  34. lastLoginCode: null,
  35. localhostUrl: null,
  36. flowStartTime: null,
  37. tabRegistry: {},
  38. sourceLastUrls: {},
  39. logs: [],
  40. ...PERSISTED_SETTING_DEFAULTS,
  41. autoRunning: false,
  42. autoRunPhase: 'idle',
  43. autoRunCurrentRun: 0,
  44. autoRunTotalRuns: 1,
  45. autoRunAttemptRun: 0,
  46. };
  47. async function getPersistedSettings() {
  48. const stored = await chrome.storage.local.get(PERSISTED_SETTING_KEYS);
  49. return {
  50. ...PERSISTED_SETTING_DEFAULTS,
  51. ...stored,
  52. autoRunSkipFailures: Boolean(stored.autoRunSkipFailures ?? PERSISTED_SETTING_DEFAULTS.autoRunSkipFailures),
  53. };
  54. }
  55. async function getState() {
  56. const [state, persistedSettings] = await Promise.all([
  57. chrome.storage.session.get(null),
  58. getPersistedSettings(),
  59. ]);
  60. return { ...DEFAULT_STATE, ...persistedSettings, ...state };
  61. }
  62. async function initializeSessionStorageAccess() {
  63. try {
  64. if (chrome.storage?.session?.setAccessLevel) {
  65. await chrome.storage.session.setAccessLevel({
  66. accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS',
  67. });
  68. console.log(LOG_PREFIX, 'Enabled storage.session for content scripts');
  69. }
  70. } catch (err) {
  71. console.warn(LOG_PREFIX, 'Failed to enable storage.session for content scripts:', err?.message || err);
  72. }
  73. }
  74. async function setState(updates) {
  75. console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
  76. await chrome.storage.session.set(updates);
  77. }
  78. async function setPersistentSettings(updates) {
  79. const persistedUpdates = {};
  80. for (const key of PERSISTED_SETTING_KEYS) {
  81. if (updates[key] !== undefined) {
  82. persistedUpdates[key] = key === 'autoRunSkipFailures'
  83. ? Boolean(updates[key])
  84. : updates[key];
  85. }
  86. }
  87. if (Object.keys(persistedUpdates).length > 0) {
  88. await chrome.storage.local.set(persistedUpdates);
  89. }
  90. }
  91. function broadcastDataUpdate(payload) {
  92. chrome.runtime.sendMessage({
  93. type: 'DATA_UPDATED',
  94. payload,
  95. }).catch(() => {});
  96. }
  97. async function setEmailState(email) {
  98. await setState({ email });
  99. broadcastDataUpdate({ email });
  100. }
  101. async function setPasswordState(password) {
  102. await setState({ password });
  103. broadcastDataUpdate({ password });
  104. }
  105. async function resetState() {
  106. console.log(LOG_PREFIX, 'Resetting all state');
  107. // Preserve settings and persistent data across resets
  108. const [prev, persistedSettings] = await Promise.all([
  109. chrome.storage.session.get([
  110. 'seenCodes',
  111. 'seenInbucketMailIds',
  112. 'accounts',
  113. 'tabRegistry',
  114. 'sourceLastUrls',
  115. ]),
  116. getPersistedSettings(),
  117. ]);
  118. await chrome.storage.session.clear();
  119. await chrome.storage.session.set({
  120. ...DEFAULT_STATE,
  121. ...persistedSettings,
  122. seenCodes: prev.seenCodes || [],
  123. seenInbucketMailIds: prev.seenInbucketMailIds || [],
  124. accounts: prev.accounts || [],
  125. tabRegistry: prev.tabRegistry || {},
  126. sourceLastUrls: prev.sourceLastUrls || {},
  127. });
  128. }
  129. /**
  130. * Generate a random password: 14 chars, mix of uppercase, lowercase, digits, symbols.
  131. */
  132. function generatePassword() {
  133. const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  134. const lower = 'abcdefghjkmnpqrstuvwxyz';
  135. const digits = '23456789';
  136. const symbols = '!@#$%&*?';
  137. const all = upper + lower + digits + symbols;
  138. // Ensure at least one of each type
  139. let pw = '';
  140. pw += upper[Math.floor(Math.random() * upper.length)];
  141. pw += lower[Math.floor(Math.random() * lower.length)];
  142. pw += digits[Math.floor(Math.random() * digits.length)];
  143. pw += symbols[Math.floor(Math.random() * symbols.length)];
  144. // Fill remaining 10 chars
  145. for (let i = 0; i < 10; i++) {
  146. pw += all[Math.floor(Math.random() * all.length)];
  147. }
  148. // Shuffle
  149. return pw.split('').sort(() => Math.random() - 0.5).join('');
  150. }
  151. // ============================================================
  152. // Tab Registry
  153. // ============================================================
  154. async function getTabRegistry() {
  155. const state = await getState();
  156. return state.tabRegistry || {};
  157. }
  158. async function registerTab(source, tabId) {
  159. const registry = await getTabRegistry();
  160. registry[source] = { tabId, ready: true };
  161. await setState({ tabRegistry: registry });
  162. console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
  163. }
  164. async function isTabAlive(source) {
  165. const registry = await getTabRegistry();
  166. const entry = registry[source];
  167. if (!entry) return false;
  168. try {
  169. await chrome.tabs.get(entry.tabId);
  170. return true;
  171. } catch {
  172. // Tab no longer exists — clean up registry
  173. registry[source] = null;
  174. await setState({ tabRegistry: registry });
  175. return false;
  176. }
  177. }
  178. async function getTabId(source) {
  179. const registry = await getTabRegistry();
  180. return registry[source]?.tabId || null;
  181. }
  182. function parseUrlSafely(rawUrl) {
  183. if (!rawUrl) return null;
  184. try {
  185. return new URL(rawUrl);
  186. } catch {
  187. return null;
  188. }
  189. }
  190. function isSignupPageHost(hostname = '') {
  191. return ['auth0.openai.com', 'auth.openai.com', 'accounts.openai.com'].includes(hostname);
  192. }
  193. function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
  194. const candidate = parseUrlSafely(candidateUrl);
  195. if (!candidate) return false;
  196. const reference = parseUrlSafely(referenceUrl);
  197. switch (source) {
  198. case 'signup-page':
  199. return isSignupPageHost(candidate.hostname);
  200. case 'duck-mail':
  201. return candidate.hostname === 'duckduckgo.com' && candidate.pathname.startsWith('/email/');
  202. case 'qq-mail':
  203. return candidate.hostname === 'mail.qq.com' || candidate.hostname === 'wx.mail.qq.com';
  204. case 'mail-163':
  205. return candidate.hostname === 'mail.163.com';
  206. case 'inbucket-mail':
  207. return Boolean(reference)
  208. && candidate.origin === reference.origin
  209. && candidate.pathname.startsWith('/m/');
  210. case 'vps-panel':
  211. return Boolean(reference) && candidate.origin === reference.origin;
  212. default:
  213. return false;
  214. }
  215. }
  216. async function rememberSourceLastUrl(source, url) {
  217. if (!source || !url) return;
  218. const state = await getState();
  219. const sourceLastUrls = { ...(state.sourceLastUrls || {}) };
  220. sourceLastUrls[source] = url;
  221. await setState({ sourceLastUrls });
  222. }
  223. async function closeConflictingTabsForSource(source, currentUrl, options = {}) {
  224. const { excludeTabIds = [] } = options;
  225. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  226. const state = await getState();
  227. const lastUrl = state.sourceLastUrls?.[source];
  228. const referenceUrls = [currentUrl, lastUrl].filter(Boolean);
  229. if (!referenceUrls.length) return;
  230. const tabs = await chrome.tabs.query({});
  231. const matchedIds = tabs
  232. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  233. .filter((tab) => referenceUrls.some((refUrl) => matchesSourceUrlFamily(source, tab.url, refUrl)))
  234. .map(tab => tab.id);
  235. if (!matchedIds.length) return;
  236. await chrome.tabs.remove(matchedIds).catch(() => {});
  237. const registry = await getTabRegistry();
  238. if (registry[source]?.tabId && matchedIds.includes(registry[source].tabId)) {
  239. registry[source] = null;
  240. await setState({ tabRegistry: registry });
  241. }
  242. await addLog(`已关闭 ${matchedIds.length} 个旧的${getSourceLabel(source)}标签页。`, 'info');
  243. }
  244. // ============================================================
  245. // Command Queue (for content scripts not yet ready)
  246. // ============================================================
  247. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  248. function queueCommand(source, message, timeout = 15000) {
  249. return new Promise((resolve, reject) => {
  250. const timer = setTimeout(() => {
  251. pendingCommands.delete(source);
  252. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  253. console.error(LOG_PREFIX, err);
  254. reject(new Error(err));
  255. }, timeout);
  256. pendingCommands.set(source, { message, resolve, reject, timer });
  257. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  258. });
  259. }
  260. function flushCommand(source, tabId) {
  261. const pending = pendingCommands.get(source);
  262. if (pending) {
  263. clearTimeout(pending.timer);
  264. pendingCommands.delete(source);
  265. chrome.tabs.sendMessage(tabId, pending.message).then(pending.resolve).catch(pending.reject);
  266. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  267. }
  268. }
  269. function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
  270. for (const [source, pending] of pendingCommands.entries()) {
  271. clearTimeout(pending.timer);
  272. pending.reject(new Error(reason));
  273. pendingCommands.delete(source);
  274. console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
  275. }
  276. }
  277. // ============================================================
  278. // Reuse or create tab
  279. // ============================================================
  280. async function reuseOrCreateTab(source, url, options = {}) {
  281. const alive = await isTabAlive(source);
  282. if (alive) {
  283. const tabId = await getTabId(source);
  284. await closeConflictingTabsForSource(source, url, { excludeTabIds: [tabId] });
  285. const currentTab = await chrome.tabs.get(tabId);
  286. const sameUrl = currentTab.url === url;
  287. const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
  288. const registry = await getTabRegistry();
  289. if (sameUrl) {
  290. await chrome.tabs.update(tabId, { active: true });
  291. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
  292. if (shouldReloadOnReuse) {
  293. if (registry[source]) registry[source].ready = false;
  294. await setState({ tabRegistry: registry });
  295. await chrome.tabs.reload(tabId);
  296. await new Promise((resolve) => {
  297. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  298. const listener = (tid, info) => {
  299. if (tid === tabId && info.status === 'complete') {
  300. chrome.tabs.onUpdated.removeListener(listener);
  301. clearTimeout(timer);
  302. resolve();
  303. }
  304. };
  305. chrome.tabs.onUpdated.addListener(listener);
  306. });
  307. }
  308. // For dynamically injected pages like the VPS panel, re-inject immediately.
  309. if (options.inject) {
  310. if (registry[source]) registry[source].ready = false;
  311. await setState({ tabRegistry: registry });
  312. if (options.injectSource) {
  313. await chrome.scripting.executeScript({
  314. target: { tabId },
  315. func: (injectedSource) => {
  316. window.__MULTIPAGE_SOURCE = injectedSource;
  317. },
  318. args: [options.injectSource],
  319. });
  320. }
  321. await chrome.scripting.executeScript({
  322. target: { tabId },
  323. files: options.inject,
  324. });
  325. await new Promise(r => setTimeout(r, 500));
  326. }
  327. await rememberSourceLastUrl(source, url);
  328. return tabId;
  329. }
  330. // Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
  331. if (registry[source]) registry[source].ready = false;
  332. await setState({ tabRegistry: registry });
  333. // Navigate existing tab to new URL
  334. await chrome.tabs.update(tabId, { url, active: true });
  335. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
  336. // Wait for page load complete (with 30s timeout)
  337. await new Promise((resolve) => {
  338. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  339. const listener = (tid, info) => {
  340. if (tid === tabId && info.status === 'complete') {
  341. chrome.tabs.onUpdated.removeListener(listener);
  342. clearTimeout(timer);
  343. resolve();
  344. }
  345. };
  346. chrome.tabs.onUpdated.addListener(listener);
  347. });
  348. // If dynamic injection needed (VPS panel), re-inject after navigation
  349. if (options.inject) {
  350. if (options.injectSource) {
  351. await chrome.scripting.executeScript({
  352. target: { tabId },
  353. func: (injectedSource) => {
  354. window.__MULTIPAGE_SOURCE = injectedSource;
  355. },
  356. args: [options.injectSource],
  357. });
  358. }
  359. await chrome.scripting.executeScript({
  360. target: { tabId },
  361. files: options.inject,
  362. });
  363. }
  364. // Wait a bit for content script to inject and send READY
  365. await new Promise(r => setTimeout(r, 500));
  366. await rememberSourceLastUrl(source, url);
  367. return tabId;
  368. }
  369. // Create new tab
  370. await closeConflictingTabsForSource(source, url);
  371. const tab = await chrome.tabs.create({ url, active: true });
  372. console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
  373. // If dynamic injection needed (VPS panel), inject scripts after load
  374. if (options.inject) {
  375. await new Promise((resolve) => {
  376. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  377. const listener = (tabId, info) => {
  378. if (tabId === tab.id && info.status === 'complete') {
  379. chrome.tabs.onUpdated.removeListener(listener);
  380. clearTimeout(timer);
  381. resolve();
  382. }
  383. };
  384. chrome.tabs.onUpdated.addListener(listener);
  385. });
  386. if (options.injectSource) {
  387. await chrome.scripting.executeScript({
  388. target: { tabId: tab.id },
  389. func: (injectedSource) => {
  390. window.__MULTIPAGE_SOURCE = injectedSource;
  391. },
  392. args: [options.injectSource],
  393. });
  394. }
  395. await chrome.scripting.executeScript({
  396. target: { tabId: tab.id },
  397. files: options.inject,
  398. });
  399. }
  400. await rememberSourceLastUrl(source, url);
  401. return tab.id;
  402. }
  403. // ============================================================
  404. // Send command to content script (with readiness check)
  405. // ============================================================
  406. async function sendToContentScript(source, message) {
  407. const registry = await getTabRegistry();
  408. const entry = registry[source];
  409. if (!entry || !entry.ready) {
  410. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  411. return queueCommand(source, message);
  412. }
  413. // Verify tab is still alive
  414. const alive = await isTabAlive(source);
  415. if (!alive) {
  416. // Tab was closed — queue the command, it will be sent when tab is reopened
  417. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  418. return queueCommand(source, message);
  419. }
  420. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  421. return chrome.tabs.sendMessage(entry.tabId, message);
  422. }
  423. // ============================================================
  424. // Logging
  425. // ============================================================
  426. async function addLog(message, level = 'info') {
  427. const state = await getState();
  428. const logs = state.logs || [];
  429. const entry = { message, level, timestamp: Date.now() };
  430. logs.push(entry);
  431. // Keep last 500 logs
  432. if (logs.length > 500) logs.splice(0, logs.length - 500);
  433. await setState({ logs });
  434. // Broadcast to side panel
  435. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => {});
  436. }
  437. function getSourceLabel(source) {
  438. const labels = {
  439. 'sidepanel': '侧边栏',
  440. 'signup-page': '认证页',
  441. 'vps-panel': 'VPS 面板',
  442. 'qq-mail': 'QQ 邮箱',
  443. 'mail-163': '163 邮箱',
  444. 'inbucket-mail': 'Inbucket 邮箱',
  445. 'duck-mail': 'Duck 邮箱',
  446. };
  447. return labels[source] || source || '未知来源';
  448. }
  449. // ============================================================
  450. // Step Status Management
  451. // ============================================================
  452. async function setStepStatus(step, status) {
  453. const state = await getState();
  454. const statuses = { ...state.stepStatuses };
  455. statuses[step] = status;
  456. await setState({ stepStatuses: statuses, currentStep: step });
  457. // Broadcast to side panel
  458. chrome.runtime.sendMessage({
  459. type: 'STEP_STATUS_CHANGED',
  460. payload: { step, status },
  461. }).catch(() => {});
  462. }
  463. function isStopError(error) {
  464. const message = typeof error === 'string' ? error : error?.message;
  465. return message === STOP_ERROR_MESSAGE;
  466. }
  467. function isStepDoneStatus(status) {
  468. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  469. }
  470. function clearStopRequest() {
  471. stopRequested = false;
  472. }
  473. function getAutoRunStatusPayload(phase, payload = {}) {
  474. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  475. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  476. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  477. const autoRunning = phase === 'running' || phase === 'waiting_email' || phase === 'retrying';
  478. return {
  479. autoRunning,
  480. autoRunPhase: phase,
  481. autoRunCurrentRun: currentRun,
  482. autoRunTotalRuns: totalRuns,
  483. autoRunAttemptRun: attemptRun,
  484. };
  485. }
  486. async function broadcastAutoRunStatus(phase, payload = {}) {
  487. const statusPayload = {
  488. phase,
  489. currentRun: payload.currentRun ?? autoRunCurrentRun,
  490. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  491. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  492. };
  493. await setState(getAutoRunStatusPayload(phase, statusPayload));
  494. chrome.runtime.sendMessage({
  495. type: 'AUTO_RUN_STATUS',
  496. payload: statusPayload,
  497. }).catch(() => {});
  498. }
  499. function isAutoRunLockedState(state) {
  500. return Boolean(state.autoRunning) && (state.autoRunPhase === 'running' || state.autoRunPhase === 'retrying');
  501. }
  502. function isAutoRunPausedState(state) {
  503. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  504. }
  505. async function ensureManualInteractionAllowed(actionLabel) {
  506. const state = await getState();
  507. if (isAutoRunLockedState(state)) {
  508. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  509. }
  510. if (isAutoRunPausedState(state)) {
  511. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  512. }
  513. return state;
  514. }
  515. async function skipStep(step) {
  516. const state = await ensureManualInteractionAllowed('跳过步骤');
  517. if (!Number.isInteger(step) || step < 1 || step > 9) {
  518. throw new Error(`无效步骤:${step}`);
  519. }
  520. const statuses = { ...(state.stepStatuses || {}) };
  521. const currentStatus = statuses[step];
  522. if (currentStatus === 'running') {
  523. throw new Error(`步骤 ${step} 正在运行中,不能跳过。`);
  524. }
  525. if (isStepDoneStatus(currentStatus)) {
  526. throw new Error(`步骤 ${step} 已完成,无需再跳过。`);
  527. }
  528. if (step > 1) {
  529. const prevStatus = statuses[step - 1];
  530. if (!isStepDoneStatus(prevStatus)) {
  531. throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`);
  532. }
  533. }
  534. await setStepStatus(step, 'skipped');
  535. await addLog(`步骤 ${step} 已跳过`, 'warn');
  536. return { ok: true, step, status: 'skipped' };
  537. }
  538. function throwIfStopped() {
  539. if (stopRequested) {
  540. throw new Error(STOP_ERROR_MESSAGE);
  541. }
  542. }
  543. async function sleepWithStop(ms) {
  544. const start = Date.now();
  545. while (Date.now() - start < ms) {
  546. throwIfStopped();
  547. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  548. }
  549. }
  550. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  551. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  552. await sleepWithStop(duration);
  553. }
  554. async function clickWithDebugger(tabId, rect) {
  555. if (!tabId) {
  556. throw new Error('未找到用于调试点击的认证页面标签页。');
  557. }
  558. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  559. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  560. }
  561. const target = { tabId };
  562. try {
  563. await chrome.debugger.attach(target, '1.3');
  564. } catch (err) {
  565. throw new Error(
  566. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  567. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  568. );
  569. }
  570. try {
  571. const x = Math.round(rect.centerX);
  572. const y = Math.round(rect.centerY);
  573. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  574. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  575. type: 'mouseMoved',
  576. x,
  577. y,
  578. button: 'none',
  579. buttons: 0,
  580. clickCount: 0,
  581. });
  582. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  583. type: 'mousePressed',
  584. x,
  585. y,
  586. button: 'left',
  587. buttons: 1,
  588. clickCount: 1,
  589. });
  590. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  591. type: 'mouseReleased',
  592. x,
  593. y,
  594. button: 'left',
  595. buttons: 0,
  596. clickCount: 1,
  597. });
  598. } finally {
  599. await chrome.debugger.detach(target).catch(() => {});
  600. }
  601. }
  602. async function broadcastStopToContentScripts() {
  603. const registry = await getTabRegistry();
  604. for (const entry of Object.values(registry)) {
  605. if (!entry?.tabId) continue;
  606. try {
  607. await chrome.tabs.sendMessage(entry.tabId, {
  608. type: 'STOP_FLOW',
  609. source: 'background',
  610. payload: {},
  611. });
  612. } catch {}
  613. }
  614. }
  615. let stopRequested = false;
  616. // ============================================================
  617. // Message Handler (central router)
  618. // ============================================================
  619. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  620. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  621. handleMessage(message, sender).then(response => {
  622. sendResponse(response);
  623. }).catch(err => {
  624. console.error(LOG_PREFIX, 'Handler error:', err);
  625. sendResponse({ error: err.message });
  626. });
  627. return true; // async response
  628. });
  629. async function handleMessage(message, sender) {
  630. switch (message.type) {
  631. case 'CONTENT_SCRIPT_READY': {
  632. const tabId = sender.tab?.id;
  633. if (tabId && message.source) {
  634. await registerTab(message.source, tabId);
  635. flushCommand(message.source, tabId);
  636. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  637. }
  638. return { ok: true };
  639. }
  640. case 'LOG': {
  641. const { message: msg, level } = message.payload;
  642. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  643. return { ok: true };
  644. }
  645. case 'STEP_COMPLETE': {
  646. if (stopRequested) {
  647. await setStepStatus(message.step, 'stopped');
  648. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  649. return { ok: true };
  650. }
  651. await setStepStatus(message.step, 'completed');
  652. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  653. await handleStepData(message.step, message.payload);
  654. notifyStepComplete(message.step, message.payload);
  655. return { ok: true };
  656. }
  657. case 'STEP_ERROR': {
  658. if (isStopError(message.error)) {
  659. await setStepStatus(message.step, 'stopped');
  660. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  661. notifyStepError(message.step, message.error);
  662. } else {
  663. await setStepStatus(message.step, 'failed');
  664. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  665. notifyStepError(message.step, message.error);
  666. }
  667. return { ok: true };
  668. }
  669. case 'GET_STATE': {
  670. return await getState();
  671. }
  672. case 'RESET': {
  673. clearStopRequest();
  674. await resetState();
  675. await addLog('流程已重置', 'info');
  676. return { ok: true };
  677. }
  678. case 'EXECUTE_STEP': {
  679. clearStopRequest();
  680. if (message.source === 'sidepanel') {
  681. await ensureManualInteractionAllowed('手动执行步骤');
  682. }
  683. const step = message.payload.step;
  684. // Save email if provided (from side panel step 3)
  685. if (message.payload.email) {
  686. await setEmailState(message.payload.email);
  687. }
  688. await executeStep(step);
  689. return { ok: true };
  690. }
  691. case 'AUTO_RUN': {
  692. clearStopRequest();
  693. const totalRuns = message.payload?.totalRuns || 1;
  694. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  695. await setState({ autoRunSkipFailures });
  696. autoRunLoop(totalRuns, { autoRunSkipFailures }); // fire-and-forget
  697. return { ok: true };
  698. }
  699. case 'RESUME_AUTO_RUN': {
  700. clearStopRequest();
  701. if (message.payload.email) {
  702. await setEmailState(message.payload.email);
  703. }
  704. resumeAutoRun(); // fire-and-forget
  705. return { ok: true };
  706. }
  707. case 'TAKEOVER_AUTO_RUN': {
  708. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  709. await addLog('自动流程已切换为手动控制。', 'warn');
  710. return { ok: true };
  711. }
  712. case 'SKIP_STEP': {
  713. const step = Number(message.payload?.step);
  714. return await skipStep(step);
  715. }
  716. case 'SAVE_SETTING': {
  717. const updates = {};
  718. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  719. if (message.payload.vpsPassword !== undefined) updates.vpsPassword = message.payload.vpsPassword;
  720. if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
  721. if (message.payload.autoRunSkipFailures !== undefined) updates.autoRunSkipFailures = Boolean(message.payload.autoRunSkipFailures);
  722. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  723. if (message.payload.inbucketHost !== undefined) updates.inbucketHost = message.payload.inbucketHost;
  724. if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
  725. await setPersistentSettings(updates);
  726. await setState(updates);
  727. return { ok: true };
  728. }
  729. // Side panel data updates
  730. case 'SAVE_EMAIL': {
  731. const state = await getState();
  732. if (isAutoRunLockedState(state)) {
  733. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  734. }
  735. await setEmailState(message.payload.email);
  736. return { ok: true, email: message.payload.email };
  737. }
  738. case 'FETCH_DUCK_EMAIL': {
  739. clearStopRequest();
  740. const state = await getState();
  741. if (isAutoRunLockedState(state)) {
  742. throw new Error('自动流程运行中,当前不能手动获取 Duck 邮箱。');
  743. }
  744. const email = await fetchDuckEmail(message.payload || {});
  745. return { ok: true, email };
  746. }
  747. case 'STOP_FLOW': {
  748. await requestStop();
  749. return { ok: true };
  750. }
  751. default:
  752. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  753. return { error: `Unknown message type: ${message.type}` };
  754. }
  755. }
  756. // ============================================================
  757. // Step Data Handlers
  758. // ============================================================
  759. async function handleStepData(step, payload) {
  760. switch (step) {
  761. case 1:
  762. if (payload.oauthUrl) {
  763. await setState({ oauthUrl: payload.oauthUrl });
  764. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  765. }
  766. break;
  767. case 3:
  768. if (payload.email) await setEmailState(payload.email);
  769. break;
  770. case 4:
  771. if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
  772. break;
  773. case 8:
  774. if (payload.localhostUrl) {
  775. await setState({ localhostUrl: payload.localhostUrl });
  776. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  777. }
  778. break;
  779. }
  780. }
  781. // ============================================================
  782. // Step Completion Waiting
  783. // ============================================================
  784. // Map of step -> { resolve, reject } for waiting on step completion
  785. const stepWaiters = new Map();
  786. let resumeWaiter = null;
  787. function waitForStepComplete(step, timeoutMs = 120000) {
  788. return new Promise((resolve, reject) => {
  789. throwIfStopped();
  790. const timer = setTimeout(() => {
  791. stepWaiters.delete(step);
  792. reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
  793. }, timeoutMs);
  794. stepWaiters.set(step, {
  795. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  796. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  797. });
  798. });
  799. }
  800. function notifyStepComplete(step, payload) {
  801. const waiter = stepWaiters.get(step);
  802. if (waiter) waiter.resolve(payload);
  803. }
  804. function notifyStepError(step, error) {
  805. const waiter = stepWaiters.get(step);
  806. if (waiter) waiter.reject(new Error(error));
  807. }
  808. async function completeStepFromBackground(step, payload = {}) {
  809. if (stopRequested) {
  810. await setStepStatus(step, 'stopped');
  811. notifyStepError(step, STOP_ERROR_MESSAGE);
  812. return;
  813. }
  814. await setStepStatus(step, 'completed');
  815. await addLog(`步骤 ${step} 已完成`, 'ok');
  816. await handleStepData(step, payload);
  817. notifyStepComplete(step, payload);
  818. }
  819. async function markRunningStepsStopped() {
  820. const state = await getState();
  821. const runningSteps = Object.entries(state.stepStatuses || {})
  822. .filter(([, status]) => status === 'running')
  823. .map(([step]) => Number(step));
  824. for (const step of runningSteps) {
  825. await setStepStatus(step, 'stopped');
  826. }
  827. }
  828. async function requestStop(options = {}) {
  829. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  830. if (stopRequested) return;
  831. stopRequested = true;
  832. cancelPendingCommands();
  833. if (webNavListener) {
  834. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  835. webNavListener = null;
  836. }
  837. await addLog(logMessage, 'warn');
  838. await broadcastStopToContentScripts();
  839. for (const waiter of stepWaiters.values()) {
  840. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  841. }
  842. stepWaiters.clear();
  843. if (resumeWaiter) {
  844. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  845. resumeWaiter = null;
  846. }
  847. await markRunningStepsStopped();
  848. autoRunActive = false;
  849. await broadcastAutoRunStatus('stopped', {
  850. currentRun: autoRunCurrentRun,
  851. totalRuns: autoRunTotalRuns,
  852. attemptRun: autoRunAttemptRun,
  853. });
  854. }
  855. // ============================================================
  856. // Step Execution
  857. // ============================================================
  858. async function executeStep(step) {
  859. console.log(LOG_PREFIX, `Executing step ${step}`);
  860. throwIfStopped();
  861. await setStepStatus(step, 'running');
  862. await addLog(`步骤 ${step} 开始执行`);
  863. await humanStepDelay();
  864. const state = await getState();
  865. // Set flow start time on first step
  866. if (step === 1 && !state.flowStartTime) {
  867. await setState({ flowStartTime: Date.now() });
  868. }
  869. try {
  870. switch (step) {
  871. case 1: await executeStep1(state); break;
  872. case 2: await executeStep2(state); break;
  873. case 3: await executeStep3(state); break;
  874. case 4: await executeStep4(state); break;
  875. case 5: await executeStep5(state); break;
  876. case 6: await executeStep6(state); break;
  877. case 7: await executeStep7(state); break;
  878. case 8: await executeStep8(state); break;
  879. case 9: await executeStep9(state); break;
  880. default:
  881. throw new Error(`未知步骤:${step}`);
  882. }
  883. } catch (err) {
  884. if (isStopError(err)) {
  885. await setStepStatus(step, 'stopped');
  886. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  887. throw err;
  888. }
  889. await setStepStatus(step, 'failed');
  890. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  891. throw err;
  892. }
  893. }
  894. /**
  895. * Execute a step and wait for it to complete before returning.
  896. * @param {number} step
  897. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  898. */
  899. async function executeStepAndWait(step, delayAfter = 2000) {
  900. throwIfStopped();
  901. const promise = waitForStepComplete(step, 120000);
  902. await executeStep(step);
  903. await promise;
  904. // Extra delay for page transitions / DOM updates
  905. if (delayAfter > 0) {
  906. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  907. }
  908. }
  909. async function fetchDuckEmail(options = {}) {
  910. throwIfStopped();
  911. const { generateNew = true } = options;
  912. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  913. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  914. const result = await sendToContentScript('duck-mail', {
  915. type: 'FETCH_DUCK_EMAIL',
  916. source: 'background',
  917. payload: { generateNew },
  918. });
  919. if (result?.error) {
  920. throw new Error(result.error);
  921. }
  922. if (!result?.email) {
  923. throw new Error('未返回 Duck 邮箱地址。');
  924. }
  925. await setEmailState(result.email);
  926. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  927. return result.email;
  928. }
  929. // ============================================================
  930. // Auto Run Flow
  931. // ============================================================
  932. let autoRunActive = false;
  933. let autoRunCurrentRun = 0;
  934. let autoRunTotalRuns = 1;
  935. let autoRunAttemptRun = 0;
  936. // Outer loop: keep retrying until the target number of successful runs is reached.
  937. async function autoRunLoop(totalRuns, options = {}) {
  938. if (autoRunActive) {
  939. await addLog('自动运行已在进行中', 'warn');
  940. return;
  941. }
  942. clearStopRequest();
  943. autoRunActive = true;
  944. autoRunTotalRuns = totalRuns;
  945. autoRunCurrentRun = 0;
  946. autoRunAttemptRun = 0;
  947. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  948. const maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  949. let successfulRuns = 0;
  950. let attemptRuns = 0;
  951. let forceFreshTabsNextRun = false;
  952. await setState({
  953. autoRunSkipFailures,
  954. ...getAutoRunStatusPayload('running', { currentRun: 0, totalRuns, attemptRun: 0 }),
  955. });
  956. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  957. attemptRuns += 1;
  958. const targetRun = successfulRuns + 1;
  959. autoRunCurrentRun = targetRun;
  960. autoRunAttemptRun = attemptRuns;
  961. // Reset everything at the start of each attempt (keep user settings).
  962. const prevState = await getState();
  963. const keepSettings = {
  964. vpsUrl: prevState.vpsUrl,
  965. vpsPassword: prevState.vpsPassword,
  966. customPassword: prevState.customPassword,
  967. autoRunSkipFailures: prevState.autoRunSkipFailures,
  968. mailProvider: prevState.mailProvider,
  969. inbucketHost: prevState.inbucketHost,
  970. inbucketMailbox: prevState.inbucketMailbox,
  971. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  972. ...(forceFreshTabsNextRun ? { tabRegistry: {} } : {}),
  973. };
  974. await resetState();
  975. await setState(keepSettings);
  976. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => {});
  977. await sleepWithStop(500);
  978. if (forceFreshTabsNextRun) {
  979. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  980. forceFreshTabsNextRun = false;
  981. }
  982. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  983. try {
  984. throwIfStopped();
  985. await broadcastAutoRunStatus('running', {
  986. currentRun: targetRun,
  987. totalRuns,
  988. attemptRun: attemptRuns,
  989. });
  990. await executeStepAndWait(1, 2000);
  991. await executeStepAndWait(2, 2000);
  992. let emailReady = false;
  993. try {
  994. const duckEmail = await fetchDuckEmail({ generateNew: true });
  995. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:Duck 邮箱已就绪:${duckEmail}(第 ${attemptRuns} 次尝试)===`, 'ok');
  996. emailReady = true;
  997. } catch (err) {
  998. await addLog(`Duck 邮箱自动获取失败:${err.message}`, 'warn');
  999. }
  1000. if (!emailReady) {
  1001. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先获取 Duck 邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  1002. await broadcastAutoRunStatus('waiting_email', {
  1003. currentRun: targetRun,
  1004. totalRuns,
  1005. attemptRun: attemptRuns,
  1006. });
  1007. await waitForResume();
  1008. const resumedState = await getState();
  1009. if (!resumedState.email) {
  1010. throw new Error('无法继续:当前没有邮箱地址。');
  1011. }
  1012. }
  1013. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  1014. await broadcastAutoRunStatus('running', {
  1015. currentRun: targetRun,
  1016. totalRuns,
  1017. attemptRun: attemptRuns,
  1018. });
  1019. const signupTabId = await getTabId('signup-page');
  1020. if (signupTabId) {
  1021. await chrome.tabs.update(signupTabId, { active: true });
  1022. }
  1023. await executeStepAndWait(3, 3000);
  1024. await executeStepAndWait(4, 2000);
  1025. await executeStepAndWait(5, 3000);
  1026. await executeStepAndWait(6, 3000);
  1027. await executeStepAndWait(7, 2000);
  1028. await executeStepAndWait(8, 2000);
  1029. await executeStepAndWait(9, 1000);
  1030. successfulRuns += 1;
  1031. autoRunCurrentRun = successfulRuns;
  1032. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  1033. continue;
  1034. } catch (err) {
  1035. if (isStopError(err)) {
  1036. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  1037. await broadcastAutoRunStatus('stopped', {
  1038. currentRun: targetRun,
  1039. totalRuns,
  1040. attemptRun: attemptRuns,
  1041. });
  1042. break;
  1043. }
  1044. if (!autoRunSkipFailures) {
  1045. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  1046. await broadcastAutoRunStatus('stopped', {
  1047. currentRun: targetRun,
  1048. totalRuns,
  1049. attemptRun: attemptRuns,
  1050. });
  1051. break;
  1052. }
  1053. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  1054. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  1055. cancelPendingCommands('当前尝试已放弃。');
  1056. await broadcastStopToContentScripts();
  1057. await broadcastAutoRunStatus('retrying', {
  1058. currentRun: targetRun,
  1059. totalRuns,
  1060. attemptRun: attemptRuns,
  1061. });
  1062. forceFreshTabsNextRun = true;
  1063. }
  1064. }
  1065. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  1066. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  1067. await broadcastAutoRunStatus('stopped', {
  1068. currentRun: successfulRuns,
  1069. totalRuns: autoRunTotalRuns,
  1070. attemptRun: attemptRuns,
  1071. });
  1072. } else if (stopRequested) {
  1073. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1074. await broadcastAutoRunStatus('stopped', {
  1075. currentRun: successfulRuns,
  1076. totalRuns: autoRunTotalRuns,
  1077. attemptRun: attemptRuns,
  1078. });
  1079. } else if (successfulRuns >= autoRunTotalRuns) {
  1080. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  1081. await broadcastAutoRunStatus('complete', {
  1082. currentRun: successfulRuns,
  1083. totalRuns: autoRunTotalRuns,
  1084. attemptRun: attemptRuns,
  1085. });
  1086. } else {
  1087. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1088. await broadcastAutoRunStatus('stopped', {
  1089. currentRun: successfulRuns,
  1090. totalRuns: autoRunTotalRuns,
  1091. attemptRun: attemptRuns,
  1092. });
  1093. }
  1094. autoRunActive = false;
  1095. autoRunAttemptRun = attemptRuns;
  1096. await setState(getAutoRunStatusPayload(stopRequested ? 'stopped' : (successfulRuns >= autoRunTotalRuns ? 'complete' : 'stopped'), {
  1097. currentRun: successfulRuns,
  1098. totalRuns: autoRunTotalRuns,
  1099. attemptRun: attemptRuns,
  1100. }));
  1101. clearStopRequest();
  1102. }
  1103. function waitForResume() {
  1104. return new Promise((resolve, reject) => {
  1105. throwIfStopped();
  1106. resumeWaiter = { resolve, reject };
  1107. });
  1108. }
  1109. async function resumeAutoRun() {
  1110. throwIfStopped();
  1111. const state = await getState();
  1112. if (!state.email) {
  1113. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  1114. return;
  1115. }
  1116. if (resumeWaiter) {
  1117. resumeWaiter.resolve();
  1118. resumeWaiter = null;
  1119. }
  1120. }
  1121. // ============================================================
  1122. // Step 1: Get OAuth Link (via vps-panel.js)
  1123. // ============================================================
  1124. async function executeStep1(state) {
  1125. if (!state.vpsUrl) {
  1126. throw new Error('尚未配置 VPS 地址,请先在侧边栏填写。');
  1127. }
  1128. await addLog('步骤 1:正在打开 VPS 面板...');
  1129. await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  1130. inject: ['content/utils.js', 'content/vps-panel.js'],
  1131. reloadIfSameUrl: true,
  1132. });
  1133. await sendToContentScript('vps-panel', {
  1134. type: 'EXECUTE_STEP',
  1135. step: 1,
  1136. source: 'background',
  1137. payload: { vpsPassword: state.vpsPassword },
  1138. });
  1139. }
  1140. // ============================================================
  1141. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  1142. // ============================================================
  1143. async function executeStep2(state) {
  1144. if (!state.oauthUrl) {
  1145. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1146. }
  1147. await addLog('步骤 2:正在打开认证链接...');
  1148. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1149. await sendToContentScript('signup-page', {
  1150. type: 'EXECUTE_STEP',
  1151. step: 2,
  1152. source: 'background',
  1153. payload: {},
  1154. });
  1155. }
  1156. // ============================================================
  1157. // Step 3: Fill Email & Password (via signup-page.js)
  1158. // ============================================================
  1159. async function executeStep3(state) {
  1160. if (!state.email) {
  1161. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  1162. }
  1163. const password = state.customPassword || generatePassword();
  1164. await setPasswordState(password);
  1165. // Save account record
  1166. const accounts = state.accounts || [];
  1167. accounts.push({ email: state.email, password, createdAt: new Date().toISOString() });
  1168. await setState({ accounts });
  1169. await addLog(
  1170. `步骤 3:正在填写邮箱 ${state.email},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  1171. );
  1172. await sendToContentScript('signup-page', {
  1173. type: 'EXECUTE_STEP',
  1174. step: 3,
  1175. source: 'background',
  1176. payload: { email: state.email, password },
  1177. });
  1178. }
  1179. // ============================================================
  1180. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  1181. // ============================================================
  1182. function getMailConfig(state) {
  1183. const provider = state.mailProvider || 'qq';
  1184. if (provider === '163') {
  1185. 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 邮箱' };
  1186. }
  1187. if (provider === 'inbucket') {
  1188. const host = normalizeInbucketOrigin(state.inbucketHost);
  1189. const mailbox = (state.inbucketMailbox || '').trim();
  1190. if (!host) {
  1191. return { error: 'Inbucket 主机地址为空或无效。' };
  1192. }
  1193. if (!mailbox) {
  1194. return { error: 'Inbucket 邮箱名称为空。' };
  1195. }
  1196. return {
  1197. source: 'inbucket-mail',
  1198. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  1199. label: `Inbucket 邮箱(${mailbox})`,
  1200. navigateOnReuse: true,
  1201. inject: ['content/utils.js', 'content/inbucket-mail.js'],
  1202. injectSource: 'inbucket-mail',
  1203. };
  1204. }
  1205. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  1206. }
  1207. function normalizeInbucketOrigin(rawValue) {
  1208. const value = (rawValue || '').trim();
  1209. if (!value) return '';
  1210. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  1211. try {
  1212. const parsed = new URL(candidate);
  1213. return parsed.origin;
  1214. } catch {
  1215. return '';
  1216. }
  1217. }
  1218. function getVerificationCodeStateKey(step) {
  1219. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  1220. }
  1221. function getVerificationCodeLabel(step) {
  1222. return step === 4 ? '注册' : '登录';
  1223. }
  1224. function getVerificationPollPayload(step, state, overrides = {}) {
  1225. if (step === 4) {
  1226. return {
  1227. filterAfterTimestamp: state.flowStartTime || 0,
  1228. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  1229. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  1230. targetEmail: state.email,
  1231. maxAttempts: 5,
  1232. intervalMs: 3000,
  1233. ...overrides,
  1234. };
  1235. }
  1236. return {
  1237. filterAfterTimestamp: state.lastEmailTimestamp || state.flowStartTime || 0,
  1238. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  1239. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  1240. targetEmail: state.email,
  1241. maxAttempts: 5,
  1242. intervalMs: 3000,
  1243. ...overrides,
  1244. };
  1245. }
  1246. async function requestVerificationCodeResend(step) {
  1247. const signupTabId = await getTabId('signup-page');
  1248. if (!signupTabId) {
  1249. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  1250. }
  1251. await chrome.tabs.update(signupTabId, { active: true });
  1252. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  1253. const result = await sendToContentScript('signup-page', {
  1254. type: 'RESEND_VERIFICATION_CODE',
  1255. step,
  1256. source: 'background',
  1257. payload: {},
  1258. });
  1259. if (result && result.error) {
  1260. throw new Error(result.error);
  1261. }
  1262. return Date.now();
  1263. }
  1264. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  1265. const stateKey = getVerificationCodeStateKey(step);
  1266. const rejectedCodes = new Set();
  1267. if (state[stateKey]) {
  1268. rejectedCodes.add(state[stateKey]);
  1269. }
  1270. for (const code of (pollOverrides.excludeCodes || [])) {
  1271. if (code) rejectedCodes.add(code);
  1272. }
  1273. let lastError = null;
  1274. let filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  1275. const maxRounds = pollOverrides.maxRounds || 3;
  1276. for (let round = 1; round <= maxRounds; round++) {
  1277. if (round > 1) {
  1278. filterAfterTimestamp = await requestVerificationCodeResend(step);
  1279. }
  1280. const payload = getVerificationPollPayload(step, state, {
  1281. ...pollOverrides,
  1282. filterAfterTimestamp,
  1283. excludeCodes: [...rejectedCodes],
  1284. });
  1285. try {
  1286. const result = await sendToContentScript(mail.source, {
  1287. type: 'POLL_EMAIL',
  1288. step,
  1289. source: 'background',
  1290. payload,
  1291. });
  1292. if (result && result.error) {
  1293. throw new Error(result.error);
  1294. }
  1295. if (!result || !result.code) {
  1296. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  1297. }
  1298. if (rejectedCodes.has(result.code)) {
  1299. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  1300. }
  1301. return result;
  1302. } catch (err) {
  1303. lastError = err;
  1304. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  1305. if (round < maxRounds) {
  1306. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  1307. }
  1308. }
  1309. }
  1310. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  1311. }
  1312. async function submitVerificationCode(step, code) {
  1313. const signupTabId = await getTabId('signup-page');
  1314. if (!signupTabId) {
  1315. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  1316. }
  1317. await chrome.tabs.update(signupTabId, { active: true });
  1318. const result = await sendToContentScript('signup-page', {
  1319. type: 'FILL_CODE',
  1320. step,
  1321. source: 'background',
  1322. payload: { code },
  1323. });
  1324. if (result && result.error) {
  1325. throw new Error(result.error);
  1326. }
  1327. return result || {};
  1328. }
  1329. async function resolveVerificationStep(step, state, mail) {
  1330. const stateKey = getVerificationCodeStateKey(step);
  1331. const rejectedCodes = new Set();
  1332. if (state[stateKey]) {
  1333. rejectedCodes.add(state[stateKey]);
  1334. }
  1335. let nextFilterAfterTimestamp = null;
  1336. const maxSubmitAttempts = 3;
  1337. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  1338. const result = await pollFreshVerificationCode(step, state, mail, {
  1339. excludeCodes: [...rejectedCodes],
  1340. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  1341. });
  1342. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  1343. const submitResult = await submitVerificationCode(step, result.code);
  1344. if (submitResult.invalidCode) {
  1345. rejectedCodes.add(result.code);
  1346. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  1347. if (attempt >= maxSubmitAttempts) {
  1348. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  1349. }
  1350. nextFilterAfterTimestamp = await requestVerificationCodeResend(step);
  1351. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  1352. continue;
  1353. }
  1354. await setState({
  1355. lastEmailTimestamp: result.emailTimestamp,
  1356. [stateKey]: result.code,
  1357. });
  1358. await completeStepFromBackground(step, {
  1359. emailTimestamp: result.emailTimestamp,
  1360. code: result.code,
  1361. });
  1362. return;
  1363. }
  1364. }
  1365. async function executeStep4(state) {
  1366. const mail = getMailConfig(state);
  1367. if (mail.error) throw new Error(mail.error);
  1368. const signupTabId = await getTabId('signup-page');
  1369. if (!signupTabId) {
  1370. throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
  1371. }
  1372. await chrome.tabs.update(signupTabId, { active: true });
  1373. await addLog('步骤 4:正在确认注册验证码页面是否就绪,必要时自动恢复密码页超时报错...');
  1374. const prepareResult = await sendToContentScript('signup-page', {
  1375. type: 'PREPARE_SIGNUP_VERIFICATION',
  1376. step: 4,
  1377. source: 'background',
  1378. payload: { password: state.password || state.customPassword || '' },
  1379. });
  1380. if (prepareResult && prepareResult.error) {
  1381. throw new Error(prepareResult.error);
  1382. }
  1383. if (prepareResult?.alreadyVerified) {
  1384. await completeStepFromBackground(4, {});
  1385. return;
  1386. }
  1387. await addLog(`步骤 4:正在打开${mail.label}...`);
  1388. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  1389. const alive = await isTabAlive(mail.source);
  1390. if (alive) {
  1391. if (mail.navigateOnReuse) {
  1392. await reuseOrCreateTab(mail.source, mail.url, {
  1393. inject: mail.inject,
  1394. injectSource: mail.injectSource,
  1395. });
  1396. } else {
  1397. const tabId = await getTabId(mail.source);
  1398. await chrome.tabs.update(tabId, { active: true });
  1399. }
  1400. } else {
  1401. await reuseOrCreateTab(mail.source, mail.url, {
  1402. inject: mail.inject,
  1403. injectSource: mail.injectSource,
  1404. });
  1405. }
  1406. await resolveVerificationStep(4, state, mail);
  1407. return;
  1408. }
  1409. // ============================================================
  1410. // Step 5: Fill Name & Birthday (via signup-page.js)
  1411. // ============================================================
  1412. async function executeStep5(state) {
  1413. const { firstName, lastName } = generateRandomName();
  1414. const { year, month, day } = generateRandomBirthday();
  1415. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  1416. await sendToContentScript('signup-page', {
  1417. type: 'EXECUTE_STEP',
  1418. step: 5,
  1419. source: 'background',
  1420. payload: { firstName, lastName, year, month, day },
  1421. });
  1422. }
  1423. // ============================================================
  1424. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  1425. // ============================================================
  1426. async function refreshOAuthUrlBeforeStep6(state) {
  1427. if (!state.vpsUrl) {
  1428. throw new Error('尚未配置 VPS 地址,请先在侧边栏填写。');
  1429. }
  1430. await addLog('步骤 6:正在刷新登录用的 OAuth 链接...');
  1431. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  1432. await executeStep1(state);
  1433. await waitForFreshOAuth;
  1434. const latestState = await getState();
  1435. if (!latestState.oauthUrl) {
  1436. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  1437. }
  1438. return latestState.oauthUrl;
  1439. }
  1440. async function executeStep6(state) {
  1441. if (!state.email) {
  1442. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  1443. }
  1444. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  1445. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  1446. // Reuse the signup-page tab — navigate it to the OAuth URL
  1447. await reuseOrCreateTab('signup-page', oauthUrl);
  1448. // signup-page.js will inject (same auth.openai.com domain) and handle login
  1449. await sendToContentScript('signup-page', {
  1450. type: 'EXECUTE_STEP',
  1451. step: 6,
  1452. source: 'background',
  1453. payload: { email: state.email, password: state.password },
  1454. });
  1455. }
  1456. // ============================================================
  1457. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  1458. // ============================================================
  1459. async function executeStep7(state) {
  1460. const mail = getMailConfig(state);
  1461. if (mail.error) throw new Error(mail.error);
  1462. const authTabId = await getTabId('signup-page');
  1463. if (authTabId) {
  1464. await chrome.tabs.update(authTabId, { active: true });
  1465. } else {
  1466. if (!state.oauthUrl) {
  1467. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1468. }
  1469. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1470. }
  1471. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  1472. const prepareResult = await sendToContentScript('signup-page', {
  1473. type: 'PREPARE_LOGIN_CODE',
  1474. step: 7,
  1475. source: 'background',
  1476. payload: {},
  1477. });
  1478. if (prepareResult && prepareResult.error) {
  1479. throw new Error(prepareResult.error);
  1480. }
  1481. await addLog(`步骤 7:正在打开${mail.label}...`);
  1482. const alive = await isTabAlive(mail.source);
  1483. if (alive) {
  1484. if (mail.navigateOnReuse) {
  1485. await reuseOrCreateTab(mail.source, mail.url, {
  1486. inject: mail.inject,
  1487. injectSource: mail.injectSource,
  1488. });
  1489. } else {
  1490. const tabId = await getTabId(mail.source);
  1491. await chrome.tabs.update(tabId, { active: true });
  1492. }
  1493. } else {
  1494. await reuseOrCreateTab(mail.source, mail.url, {
  1495. inject: mail.inject,
  1496. injectSource: mail.injectSource,
  1497. });
  1498. }
  1499. await resolveVerificationStep(7, state, mail);
  1500. return;
  1501. }
  1502. // ============================================================
  1503. // Step 8: Complete OAuth (auto click + localhost listener)
  1504. // ============================================================
  1505. let webNavListener = null;
  1506. async function executeStep8(state) {
  1507. if (!state.oauthUrl) {
  1508. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1509. }
  1510. await addLog('步骤 8:正在监听 localhost 回调地址...');
  1511. // Register webNavigation listener (scoped to this step)
  1512. return new Promise((resolve, reject) => {
  1513. let resolved = false;
  1514. let resolveCaptureWait = null;
  1515. const captureWait = new Promise((resolveCapture) => {
  1516. resolveCaptureWait = resolveCapture;
  1517. });
  1518. const cleanupListener = () => {
  1519. if (webNavListener) {
  1520. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  1521. webNavListener = null;
  1522. }
  1523. };
  1524. const timeout = setTimeout(() => {
  1525. cleanupListener();
  1526. reject(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  1527. }, 120000);
  1528. webNavListener = (details) => {
  1529. if (details.url.startsWith('http://localhost')) {
  1530. console.log(LOG_PREFIX, `Captured localhost redirect: ${details.url}`);
  1531. resolved = true;
  1532. cleanupListener();
  1533. clearTimeout(timeout);
  1534. if (resolveCaptureWait) resolveCaptureWait(details.url);
  1535. setState({ localhostUrl: details.url }).then(() => {
  1536. addLog(`步骤 8:已捕获 localhost 地址:${details.url}`, 'ok');
  1537. setStepStatus(8, 'completed');
  1538. notifyStepComplete(8, { localhostUrl: details.url });
  1539. broadcastDataUpdate({ localhostUrl: details.url });
  1540. resolve();
  1541. });
  1542. }
  1543. };
  1544. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  1545. // After step 7, the auth page shows a consent screen ("使用 ChatGPT 登录到 Codex")
  1546. // with a "继续" button. We locate the button in-page, then click it through
  1547. // the debugger Input API directly.
  1548. (async () => {
  1549. try {
  1550. let signupTabId = await getTabId('signup-page');
  1551. if (signupTabId) {
  1552. await chrome.tabs.update(signupTabId, { active: true });
  1553. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  1554. } else {
  1555. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  1556. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  1557. }
  1558. const clickResult = await sendToContentScript('signup-page', {
  1559. type: 'STEP8_FIND_AND_CLICK',
  1560. source: 'background',
  1561. payload: {},
  1562. });
  1563. if (clickResult?.error) {
  1564. throw new Error(clickResult.error);
  1565. }
  1566. if (!resolved) {
  1567. await clickWithDebugger(signupTabId, clickResult?.rect);
  1568. await addLog('步骤 8:已发送调试器点击,正在等待跳转...');
  1569. }
  1570. } catch (err) {
  1571. clearTimeout(timeout);
  1572. cleanupListener();
  1573. reject(err);
  1574. }
  1575. })();
  1576. });
  1577. }
  1578. // ============================================================
  1579. // Step 9: VPS Verify (via vps-panel.js)
  1580. // ============================================================
  1581. async function executeStep9(state) {
  1582. if (!state.localhostUrl) {
  1583. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  1584. }
  1585. if (!state.vpsUrl) {
  1586. throw new Error('尚未填写 VPS 地址,请先在侧边栏输入。');
  1587. }
  1588. await addLog('步骤 9:正在打开 VPS 面板...');
  1589. let tabId = await getTabId('vps-panel');
  1590. const alive = tabId && await isTabAlive('vps-panel');
  1591. if (!alive) {
  1592. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  1593. // Create new tab
  1594. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  1595. tabId = tab.id;
  1596. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  1597. await new Promise(resolve => {
  1598. const listener = (tid, info) => {
  1599. if (tid === tabId && info.status === 'complete') {
  1600. chrome.tabs.onUpdated.removeListener(listener);
  1601. resolve();
  1602. }
  1603. };
  1604. chrome.tabs.onUpdated.addListener(listener);
  1605. });
  1606. } else {
  1607. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  1608. await chrome.tabs.update(tabId, { active: true });
  1609. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  1610. }
  1611. // Inject scripts directly and wait for them to be ready
  1612. await chrome.scripting.executeScript({
  1613. target: { tabId },
  1614. files: ['content/utils.js', 'content/vps-panel.js'],
  1615. });
  1616. await new Promise(r => setTimeout(r, 1000));
  1617. // Send command directly — bypass queue/ready mechanism
  1618. await addLog('步骤 9:正在填写回调地址...');
  1619. await chrome.tabs.sendMessage(tabId, {
  1620. type: 'EXECUTE_STEP',
  1621. step: 9,
  1622. source: 'background',
  1623. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  1624. });
  1625. }
  1626. // ============================================================
  1627. // Open Side Panel on extension icon click
  1628. // ============================================================
  1629. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });