background.js 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  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. await addLog(`步骤 4:正在打开${mail.label}...`);
  1369. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  1370. const alive = await isTabAlive(mail.source);
  1371. if (alive) {
  1372. if (mail.navigateOnReuse) {
  1373. await reuseOrCreateTab(mail.source, mail.url, {
  1374. inject: mail.inject,
  1375. injectSource: mail.injectSource,
  1376. });
  1377. } else {
  1378. const tabId = await getTabId(mail.source);
  1379. await chrome.tabs.update(tabId, { active: true });
  1380. }
  1381. } else {
  1382. await reuseOrCreateTab(mail.source, mail.url, {
  1383. inject: mail.inject,
  1384. injectSource: mail.injectSource,
  1385. });
  1386. }
  1387. await resolveVerificationStep(4, state, mail);
  1388. return;
  1389. }
  1390. // ============================================================
  1391. // Step 5: Fill Name & Birthday (via signup-page.js)
  1392. // ============================================================
  1393. async function executeStep5(state) {
  1394. const { firstName, lastName } = generateRandomName();
  1395. const { year, month, day } = generateRandomBirthday();
  1396. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  1397. await sendToContentScript('signup-page', {
  1398. type: 'EXECUTE_STEP',
  1399. step: 5,
  1400. source: 'background',
  1401. payload: { firstName, lastName, year, month, day },
  1402. });
  1403. }
  1404. // ============================================================
  1405. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  1406. // ============================================================
  1407. async function refreshOAuthUrlBeforeStep6(state) {
  1408. if (!state.vpsUrl) {
  1409. throw new Error('尚未配置 VPS 地址,请先在侧边栏填写。');
  1410. }
  1411. await addLog('步骤 6:正在刷新登录用的 OAuth 链接...');
  1412. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  1413. await executeStep1(state);
  1414. await waitForFreshOAuth;
  1415. const latestState = await getState();
  1416. if (!latestState.oauthUrl) {
  1417. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  1418. }
  1419. return latestState.oauthUrl;
  1420. }
  1421. async function executeStep6(state) {
  1422. if (!state.email) {
  1423. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  1424. }
  1425. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  1426. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  1427. // Reuse the signup-page tab — navigate it to the OAuth URL
  1428. await reuseOrCreateTab('signup-page', oauthUrl);
  1429. // signup-page.js will inject (same auth.openai.com domain) and handle login
  1430. await sendToContentScript('signup-page', {
  1431. type: 'EXECUTE_STEP',
  1432. step: 6,
  1433. source: 'background',
  1434. payload: { email: state.email, password: state.password },
  1435. });
  1436. }
  1437. // ============================================================
  1438. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  1439. // ============================================================
  1440. async function executeStep7(state) {
  1441. const mail = getMailConfig(state);
  1442. if (mail.error) throw new Error(mail.error);
  1443. const authTabId = await getTabId('signup-page');
  1444. if (authTabId) {
  1445. await chrome.tabs.update(authTabId, { active: true });
  1446. } else {
  1447. if (!state.oauthUrl) {
  1448. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1449. }
  1450. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1451. }
  1452. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  1453. const prepareResult = await sendToContentScript('signup-page', {
  1454. type: 'PREPARE_LOGIN_CODE',
  1455. step: 7,
  1456. source: 'background',
  1457. payload: {},
  1458. });
  1459. if (prepareResult && prepareResult.error) {
  1460. throw new Error(prepareResult.error);
  1461. }
  1462. await addLog(`步骤 7:正在打开${mail.label}...`);
  1463. const alive = await isTabAlive(mail.source);
  1464. if (alive) {
  1465. if (mail.navigateOnReuse) {
  1466. await reuseOrCreateTab(mail.source, mail.url, {
  1467. inject: mail.inject,
  1468. injectSource: mail.injectSource,
  1469. });
  1470. } else {
  1471. const tabId = await getTabId(mail.source);
  1472. await chrome.tabs.update(tabId, { active: true });
  1473. }
  1474. } else {
  1475. await reuseOrCreateTab(mail.source, mail.url, {
  1476. inject: mail.inject,
  1477. injectSource: mail.injectSource,
  1478. });
  1479. }
  1480. await resolveVerificationStep(7, state, mail);
  1481. return;
  1482. }
  1483. // ============================================================
  1484. // Step 8: Complete OAuth (auto click + localhost listener)
  1485. // ============================================================
  1486. let webNavListener = null;
  1487. async function executeStep8(state) {
  1488. if (!state.oauthUrl) {
  1489. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1490. }
  1491. await addLog('步骤 8:正在监听 localhost 回调地址...');
  1492. // Register webNavigation listener (scoped to this step)
  1493. return new Promise((resolve, reject) => {
  1494. let resolved = false;
  1495. let resolveCaptureWait = null;
  1496. const captureWait = new Promise((resolveCapture) => {
  1497. resolveCaptureWait = resolveCapture;
  1498. });
  1499. const cleanupListener = () => {
  1500. if (webNavListener) {
  1501. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  1502. webNavListener = null;
  1503. }
  1504. };
  1505. const timeout = setTimeout(() => {
  1506. cleanupListener();
  1507. reject(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  1508. }, 120000);
  1509. webNavListener = (details) => {
  1510. if (details.url.startsWith('http://localhost')) {
  1511. console.log(LOG_PREFIX, `Captured localhost redirect: ${details.url}`);
  1512. resolved = true;
  1513. cleanupListener();
  1514. clearTimeout(timeout);
  1515. if (resolveCaptureWait) resolveCaptureWait(details.url);
  1516. setState({ localhostUrl: details.url }).then(() => {
  1517. addLog(`步骤 8:已捕获 localhost 地址:${details.url}`, 'ok');
  1518. setStepStatus(8, 'completed');
  1519. notifyStepComplete(8, { localhostUrl: details.url });
  1520. broadcastDataUpdate({ localhostUrl: details.url });
  1521. resolve();
  1522. });
  1523. }
  1524. };
  1525. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  1526. // After step 7, the auth page shows a consent screen ("使用 ChatGPT 登录到 Codex")
  1527. // with a "继续" button. We locate the button in-page, then click it through
  1528. // the debugger Input API directly.
  1529. (async () => {
  1530. try {
  1531. let signupTabId = await getTabId('signup-page');
  1532. if (signupTabId) {
  1533. await chrome.tabs.update(signupTabId, { active: true });
  1534. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  1535. } else {
  1536. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  1537. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  1538. }
  1539. const clickResult = await sendToContentScript('signup-page', {
  1540. type: 'STEP8_FIND_AND_CLICK',
  1541. source: 'background',
  1542. payload: {},
  1543. });
  1544. if (clickResult?.error) {
  1545. throw new Error(clickResult.error);
  1546. }
  1547. if (!resolved) {
  1548. await clickWithDebugger(signupTabId, clickResult?.rect);
  1549. await addLog('步骤 8:已发送调试器点击,正在等待跳转...');
  1550. }
  1551. } catch (err) {
  1552. clearTimeout(timeout);
  1553. cleanupListener();
  1554. reject(err);
  1555. }
  1556. })();
  1557. });
  1558. }
  1559. // ============================================================
  1560. // Step 9: VPS Verify (via vps-panel.js)
  1561. // ============================================================
  1562. async function executeStep9(state) {
  1563. if (!state.localhostUrl) {
  1564. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  1565. }
  1566. if (!state.vpsUrl) {
  1567. throw new Error('尚未填写 VPS 地址,请先在侧边栏输入。');
  1568. }
  1569. await addLog('步骤 9:正在打开 VPS 面板...');
  1570. let tabId = await getTabId('vps-panel');
  1571. const alive = tabId && await isTabAlive('vps-panel');
  1572. if (!alive) {
  1573. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  1574. // Create new tab
  1575. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  1576. tabId = tab.id;
  1577. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  1578. await new Promise(resolve => {
  1579. const listener = (tid, info) => {
  1580. if (tid === tabId && info.status === 'complete') {
  1581. chrome.tabs.onUpdated.removeListener(listener);
  1582. resolve();
  1583. }
  1584. };
  1585. chrome.tabs.onUpdated.addListener(listener);
  1586. });
  1587. } else {
  1588. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  1589. await chrome.tabs.update(tabId, { active: true });
  1590. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  1591. }
  1592. // Inject scripts directly and wait for them to be ready
  1593. await chrome.scripting.executeScript({
  1594. target: { tabId },
  1595. files: ['content/utils.js', 'content/vps-panel.js'],
  1596. });
  1597. await new Promise(r => setTimeout(r, 1000));
  1598. // Send command directly — bypass queue/ready mechanism
  1599. await addLog('步骤 9:正在填写回调地址...');
  1600. await chrome.tabs.sendMessage(tabId, {
  1601. type: 'EXECUTE_STEP',
  1602. step: 9,
  1603. source: 'background',
  1604. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  1605. });
  1606. }
  1607. // ============================================================
  1608. // Open Side Panel on extension icon click
  1609. // ============================================================
  1610. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });