background.js 62 KB

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