background.js 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042
  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 getFirstUnfinishedStep(statuses = {}) {
  497. for (let step = 1; step <= 9; step++) {
  498. if (!isStepDoneStatus(statuses[step] || 'pending')) {
  499. return step;
  500. }
  501. }
  502. return null;
  503. }
  504. function hasSavedProgress(statuses = {}) {
  505. return Object.values({ ...DEFAULT_STATE.stepStatuses, ...statuses }).some((status) => status !== 'pending');
  506. }
  507. function clearStopRequest() {
  508. stopRequested = false;
  509. }
  510. function getAutoRunStatusPayload(phase, payload = {}) {
  511. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  512. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  513. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  514. const autoRunning = phase === 'running' || phase === 'waiting_email' || phase === 'retrying';
  515. return {
  516. autoRunning,
  517. autoRunPhase: phase,
  518. autoRunCurrentRun: currentRun,
  519. autoRunTotalRuns: totalRuns,
  520. autoRunAttemptRun: attemptRun,
  521. };
  522. }
  523. async function broadcastAutoRunStatus(phase, payload = {}) {
  524. const statusPayload = {
  525. phase,
  526. currentRun: payload.currentRun ?? autoRunCurrentRun,
  527. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  528. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  529. };
  530. await setState(getAutoRunStatusPayload(phase, statusPayload));
  531. chrome.runtime.sendMessage({
  532. type: 'AUTO_RUN_STATUS',
  533. payload: statusPayload,
  534. }).catch(() => {});
  535. }
  536. function isAutoRunLockedState(state) {
  537. return Boolean(state.autoRunning) && (state.autoRunPhase === 'running' || state.autoRunPhase === 'retrying');
  538. }
  539. function isAutoRunPausedState(state) {
  540. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  541. }
  542. async function ensureManualInteractionAllowed(actionLabel) {
  543. const state = await getState();
  544. if (isAutoRunLockedState(state)) {
  545. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  546. }
  547. if (isAutoRunPausedState(state)) {
  548. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  549. }
  550. return state;
  551. }
  552. async function skipStep(step) {
  553. const state = await ensureManualInteractionAllowed('跳过步骤');
  554. if (!Number.isInteger(step) || step < 1 || step > 9) {
  555. throw new Error(`无效步骤:${step}`);
  556. }
  557. const statuses = { ...(state.stepStatuses || {}) };
  558. const currentStatus = statuses[step];
  559. if (currentStatus === 'running') {
  560. throw new Error(`步骤 ${step} 正在运行中,不能跳过。`);
  561. }
  562. if (isStepDoneStatus(currentStatus)) {
  563. throw new Error(`步骤 ${step} 已完成,无需再跳过。`);
  564. }
  565. if (step > 1) {
  566. const prevStatus = statuses[step - 1];
  567. if (!isStepDoneStatus(prevStatus)) {
  568. throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`);
  569. }
  570. }
  571. await setStepStatus(step, 'skipped');
  572. await addLog(`步骤 ${step} 已跳过`, 'warn');
  573. if (step === 1) {
  574. const latestState = await getState();
  575. const step2Status = latestState.stepStatuses?.[2];
  576. if (!isStepDoneStatus(step2Status) && step2Status !== 'running') {
  577. await setStepStatus(2, 'skipped');
  578. await addLog('步骤 1 已跳过,步骤 2 也已同时跳过。', 'warn');
  579. }
  580. }
  581. return { ok: true, step, status: 'skipped' };
  582. }
  583. function throwIfStopped() {
  584. if (stopRequested) {
  585. throw new Error(STOP_ERROR_MESSAGE);
  586. }
  587. }
  588. async function sleepWithStop(ms) {
  589. const start = Date.now();
  590. while (Date.now() - start < ms) {
  591. throwIfStopped();
  592. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  593. }
  594. }
  595. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  596. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  597. await sleepWithStop(duration);
  598. }
  599. async function clickWithDebugger(tabId, rect) {
  600. if (!tabId) {
  601. throw new Error('未找到用于调试点击的认证页面标签页。');
  602. }
  603. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  604. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  605. }
  606. const target = { tabId };
  607. try {
  608. await chrome.debugger.attach(target, '1.3');
  609. } catch (err) {
  610. throw new Error(
  611. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  612. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  613. );
  614. }
  615. try {
  616. const x = Math.round(rect.centerX);
  617. const y = Math.round(rect.centerY);
  618. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  619. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  620. type: 'mouseMoved',
  621. x,
  622. y,
  623. button: 'none',
  624. buttons: 0,
  625. clickCount: 0,
  626. });
  627. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  628. type: 'mousePressed',
  629. x,
  630. y,
  631. button: 'left',
  632. buttons: 1,
  633. clickCount: 1,
  634. });
  635. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  636. type: 'mouseReleased',
  637. x,
  638. y,
  639. button: 'left',
  640. buttons: 0,
  641. clickCount: 1,
  642. });
  643. } finally {
  644. await chrome.debugger.detach(target).catch(() => {});
  645. }
  646. }
  647. async function broadcastStopToContentScripts() {
  648. const registry = await getTabRegistry();
  649. for (const entry of Object.values(registry)) {
  650. if (!entry?.tabId) continue;
  651. try {
  652. await chrome.tabs.sendMessage(entry.tabId, {
  653. type: 'STOP_FLOW',
  654. source: 'background',
  655. payload: {},
  656. });
  657. } catch {}
  658. }
  659. }
  660. let stopRequested = false;
  661. // ============================================================
  662. // Message Handler (central router)
  663. // ============================================================
  664. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  665. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  666. handleMessage(message, sender).then(response => {
  667. sendResponse(response);
  668. }).catch(err => {
  669. console.error(LOG_PREFIX, 'Handler error:', err);
  670. sendResponse({ error: err.message });
  671. });
  672. return true; // async response
  673. });
  674. async function handleMessage(message, sender) {
  675. switch (message.type) {
  676. case 'CONTENT_SCRIPT_READY': {
  677. const tabId = sender.tab?.id;
  678. if (tabId && message.source) {
  679. await registerTab(message.source, tabId);
  680. flushCommand(message.source, tabId);
  681. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  682. }
  683. return { ok: true };
  684. }
  685. case 'LOG': {
  686. const { message: msg, level } = message.payload;
  687. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  688. return { ok: true };
  689. }
  690. case 'STEP_COMPLETE': {
  691. if (stopRequested) {
  692. await setStepStatus(message.step, 'stopped');
  693. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  694. return { ok: true };
  695. }
  696. await setStepStatus(message.step, 'completed');
  697. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  698. await handleStepData(message.step, message.payload);
  699. notifyStepComplete(message.step, message.payload);
  700. return { ok: true };
  701. }
  702. case 'STEP_ERROR': {
  703. if (isStopError(message.error)) {
  704. await setStepStatus(message.step, 'stopped');
  705. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  706. notifyStepError(message.step, message.error);
  707. } else {
  708. await setStepStatus(message.step, 'failed');
  709. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  710. notifyStepError(message.step, message.error);
  711. }
  712. return { ok: true };
  713. }
  714. case 'GET_STATE': {
  715. return await getState();
  716. }
  717. case 'RESET': {
  718. clearStopRequest();
  719. await resetState();
  720. await addLog('流程已重置', 'info');
  721. return { ok: true };
  722. }
  723. case 'EXECUTE_STEP': {
  724. clearStopRequest();
  725. if (message.source === 'sidepanel') {
  726. await ensureManualInteractionAllowed('手动执行步骤');
  727. }
  728. const step = message.payload.step;
  729. // Save email if provided (from side panel step 3)
  730. if (message.payload.email) {
  731. await setEmailState(message.payload.email);
  732. }
  733. await executeStep(step);
  734. return { ok: true };
  735. }
  736. case 'AUTO_RUN': {
  737. clearStopRequest();
  738. const totalRuns = message.payload?.totalRuns || 1;
  739. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  740. const mode = message.payload?.mode === 'continue' ? 'continue' : 'restart';
  741. await setState({ autoRunSkipFailures });
  742. autoRunLoop(totalRuns, { autoRunSkipFailures, mode }); // fire-and-forget
  743. return { ok: true };
  744. }
  745. case 'RESUME_AUTO_RUN': {
  746. clearStopRequest();
  747. if (message.payload.email) {
  748. await setEmailState(message.payload.email);
  749. }
  750. resumeAutoRun(); // fire-and-forget
  751. return { ok: true };
  752. }
  753. case 'TAKEOVER_AUTO_RUN': {
  754. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  755. await addLog('自动流程已切换为手动控制。', 'warn');
  756. return { ok: true };
  757. }
  758. case 'SKIP_STEP': {
  759. const step = Number(message.payload?.step);
  760. return await skipStep(step);
  761. }
  762. case 'SAVE_SETTING': {
  763. const updates = {};
  764. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  765. if (message.payload.vpsPassword !== undefined) updates.vpsPassword = message.payload.vpsPassword;
  766. if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
  767. if (message.payload.autoRunSkipFailures !== undefined) updates.autoRunSkipFailures = Boolean(message.payload.autoRunSkipFailures);
  768. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  769. if (message.payload.inbucketHost !== undefined) updates.inbucketHost = message.payload.inbucketHost;
  770. if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
  771. await setPersistentSettings(updates);
  772. await setState(updates);
  773. return { ok: true };
  774. }
  775. // Side panel data updates
  776. case 'SAVE_EMAIL': {
  777. const state = await getState();
  778. if (isAutoRunLockedState(state)) {
  779. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  780. }
  781. await setEmailState(message.payload.email);
  782. return { ok: true, email: message.payload.email };
  783. }
  784. case 'FETCH_DUCK_EMAIL': {
  785. clearStopRequest();
  786. const state = await getState();
  787. if (isAutoRunLockedState(state)) {
  788. throw new Error('自动流程运行中,当前不能手动获取 Duck 邮箱。');
  789. }
  790. const email = await fetchDuckEmail(message.payload || {});
  791. return { ok: true, email };
  792. }
  793. case 'STOP_FLOW': {
  794. await requestStop();
  795. return { ok: true };
  796. }
  797. default:
  798. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  799. return { error: `Unknown message type: ${message.type}` };
  800. }
  801. }
  802. // ============================================================
  803. // Step Data Handlers
  804. // ============================================================
  805. async function handleStepData(step, payload) {
  806. switch (step) {
  807. case 1:
  808. if (payload.oauthUrl) {
  809. await setState({ oauthUrl: payload.oauthUrl });
  810. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  811. }
  812. break;
  813. case 3:
  814. if (payload.email) await setEmailState(payload.email);
  815. break;
  816. case 4:
  817. if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
  818. break;
  819. case 8:
  820. if (payload.localhostUrl) {
  821. await setState({ localhostUrl: payload.localhostUrl });
  822. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  823. }
  824. break;
  825. case 9: {
  826. const localhostPrefix = buildLocalhostCleanupPrefix(payload.localhostUrl);
  827. if (localhostPrefix) {
  828. await closeTabsByUrlPrefix(localhostPrefix);
  829. }
  830. break;
  831. }
  832. }
  833. }
  834. // ============================================================
  835. // Step Completion Waiting
  836. // ============================================================
  837. // Map of step -> { resolve, reject } for waiting on step completion
  838. const stepWaiters = new Map();
  839. let resumeWaiter = null;
  840. function waitForStepComplete(step, timeoutMs = 120000) {
  841. return new Promise((resolve, reject) => {
  842. throwIfStopped();
  843. const timer = setTimeout(() => {
  844. stepWaiters.delete(step);
  845. reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
  846. }, timeoutMs);
  847. stepWaiters.set(step, {
  848. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  849. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  850. });
  851. });
  852. }
  853. function notifyStepComplete(step, payload) {
  854. const waiter = stepWaiters.get(step);
  855. if (waiter) waiter.resolve(payload);
  856. }
  857. function notifyStepError(step, error) {
  858. const waiter = stepWaiters.get(step);
  859. if (waiter) waiter.reject(new Error(error));
  860. }
  861. async function completeStepFromBackground(step, payload = {}) {
  862. if (stopRequested) {
  863. await setStepStatus(step, 'stopped');
  864. notifyStepError(step, STOP_ERROR_MESSAGE);
  865. return;
  866. }
  867. await setStepStatus(step, 'completed');
  868. await addLog(`步骤 ${step} 已完成`, 'ok');
  869. await handleStepData(step, payload);
  870. notifyStepComplete(step, payload);
  871. }
  872. async function markRunningStepsStopped() {
  873. const state = await getState();
  874. const runningSteps = Object.entries(state.stepStatuses || {})
  875. .filter(([, status]) => status === 'running')
  876. .map(([step]) => Number(step));
  877. for (const step of runningSteps) {
  878. await setStepStatus(step, 'stopped');
  879. }
  880. }
  881. async function requestStop(options = {}) {
  882. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  883. if (stopRequested) return;
  884. stopRequested = true;
  885. cancelPendingCommands();
  886. if (webNavListener) {
  887. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  888. webNavListener = null;
  889. }
  890. await addLog(logMessage, 'warn');
  891. await broadcastStopToContentScripts();
  892. for (const waiter of stepWaiters.values()) {
  893. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  894. }
  895. stepWaiters.clear();
  896. if (resumeWaiter) {
  897. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  898. resumeWaiter = null;
  899. }
  900. await markRunningStepsStopped();
  901. autoRunActive = false;
  902. await broadcastAutoRunStatus('stopped', {
  903. currentRun: autoRunCurrentRun,
  904. totalRuns: autoRunTotalRuns,
  905. attemptRun: autoRunAttemptRun,
  906. });
  907. }
  908. // ============================================================
  909. // Step Execution
  910. // ============================================================
  911. async function executeStep(step) {
  912. console.log(LOG_PREFIX, `Executing step ${step}`);
  913. throwIfStopped();
  914. await setStepStatus(step, 'running');
  915. await addLog(`步骤 ${step} 开始执行`);
  916. await humanStepDelay();
  917. const state = await getState();
  918. // Set flow start time on first step
  919. if (step === 1 && !state.flowStartTime) {
  920. await setState({ flowStartTime: Date.now() });
  921. }
  922. try {
  923. switch (step) {
  924. case 1: await executeStep1(state); break;
  925. case 2: await executeStep2(state); break;
  926. case 3: await executeStep3(state); break;
  927. case 4: await executeStep4(state); break;
  928. case 5: await executeStep5(state); break;
  929. case 6: await executeStep6(state); break;
  930. case 7: await executeStep7(state); break;
  931. case 8: await executeStep8(state); break;
  932. case 9: await executeStep9(state); break;
  933. default:
  934. throw new Error(`未知步骤:${step}`);
  935. }
  936. } catch (err) {
  937. if (isStopError(err)) {
  938. await setStepStatus(step, 'stopped');
  939. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  940. throw err;
  941. }
  942. await setStepStatus(step, 'failed');
  943. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  944. throw err;
  945. }
  946. }
  947. /**
  948. * Execute a step and wait for it to complete before returning.
  949. * @param {number} step
  950. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  951. */
  952. async function executeStepAndWait(step, delayAfter = 2000) {
  953. throwIfStopped();
  954. const promise = waitForStepComplete(step, 120000);
  955. await executeStep(step);
  956. await promise;
  957. // Extra delay for page transitions / DOM updates
  958. if (delayAfter > 0) {
  959. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  960. }
  961. }
  962. async function fetchDuckEmail(options = {}) {
  963. throwIfStopped();
  964. const { generateNew = true } = options;
  965. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  966. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  967. const result = await sendToContentScript('duck-mail', {
  968. type: 'FETCH_DUCK_EMAIL',
  969. source: 'background',
  970. payload: { generateNew },
  971. });
  972. if (result?.error) {
  973. throw new Error(result.error);
  974. }
  975. if (!result?.email) {
  976. throw new Error('未返回 Duck 邮箱地址。');
  977. }
  978. await setEmailState(result.email);
  979. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  980. return result.email;
  981. }
  982. // ============================================================
  983. // Auto Run Flow
  984. // ============================================================
  985. let autoRunActive = false;
  986. let autoRunCurrentRun = 0;
  987. let autoRunTotalRuns = 1;
  988. let autoRunAttemptRun = 0;
  989. const AUTO_STEP_DELAYS = {
  990. 1: 2000,
  991. 2: 2000,
  992. 3: 3000,
  993. 4: 2000,
  994. 5: 3000,
  995. 6: 3000,
  996. 7: 2000,
  997. 8: 2000,
  998. 9: 1000,
  999. };
  1000. async function resumeAutoRunIfWaitingForEmail(options = {}) {
  1001. const { silent = false } = options;
  1002. const state = await getState();
  1003. if (!state.email || !isAutoRunPausedState(state)) {
  1004. return false;
  1005. }
  1006. if (resumeWaiter) {
  1007. if (!silent) {
  1008. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  1009. }
  1010. resumeWaiter.resolve();
  1011. resumeWaiter = null;
  1012. return true;
  1013. }
  1014. return false;
  1015. }
  1016. async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
  1017. const currentState = await getState();
  1018. if (currentState.email) {
  1019. return currentState.email;
  1020. }
  1021. try {
  1022. const duckEmail = await fetchDuckEmail({ generateNew: true });
  1023. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:Duck 邮箱已就绪:${duckEmail}(第 ${attemptRuns} 次尝试)===`, 'ok');
  1024. return duckEmail;
  1025. } catch (err) {
  1026. await addLog(`Duck 邮箱自动获取失败:${err.message}`, 'warn');
  1027. }
  1028. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先获取 Duck 邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  1029. await broadcastAutoRunStatus('waiting_email', {
  1030. currentRun: targetRun,
  1031. totalRuns,
  1032. attemptRun: attemptRuns,
  1033. });
  1034. await waitForResume();
  1035. const resumedState = await getState();
  1036. if (!resumedState.email) {
  1037. throw new Error('无法继续:当前没有邮箱地址。');
  1038. }
  1039. return resumedState.email;
  1040. }
  1041. async function runAutoSequenceFromStep(startStep, context = {}) {
  1042. const { targetRun, totalRuns, attemptRuns, continued = false } = context;
  1043. if (continued) {
  1044. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续当前进度,从步骤 ${startStep} 开始(第 ${attemptRuns} 次尝试)===`, 'info');
  1045. } else {
  1046. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  1047. }
  1048. if (startStep <= 2) {
  1049. for (const step of [1, 2]) {
  1050. if (step < startStep) continue;
  1051. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1052. }
  1053. }
  1054. if (startStep <= 3) {
  1055. await ensureAutoEmailReady(targetRun, totalRuns, attemptRuns);
  1056. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  1057. await broadcastAutoRunStatus('running', {
  1058. currentRun: targetRun,
  1059. totalRuns,
  1060. attemptRun: attemptRuns,
  1061. });
  1062. await executeStepAndWait(3, AUTO_STEP_DELAYS[3]);
  1063. } else {
  1064. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续执行剩余流程(第 ${attemptRuns} 次尝试)===`, 'info');
  1065. }
  1066. const signupTabId = await getTabId('signup-page');
  1067. if (signupTabId) {
  1068. await chrome.tabs.update(signupTabId, { active: true });
  1069. }
  1070. for (let step = Math.max(startStep, 4); step <= 9; step++) {
  1071. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1072. }
  1073. }
  1074. // Outer loop: keep retrying until the target number of successful runs is reached.
  1075. async function autoRunLoop(totalRuns, options = {}) {
  1076. if (autoRunActive) {
  1077. await addLog('自动运行已在进行中', 'warn');
  1078. return;
  1079. }
  1080. clearStopRequest();
  1081. autoRunActive = true;
  1082. autoRunTotalRuns = totalRuns;
  1083. autoRunCurrentRun = 0;
  1084. autoRunAttemptRun = 0;
  1085. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  1086. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  1087. const maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  1088. let successfulRuns = 0;
  1089. let attemptRuns = 0;
  1090. let forceFreshTabsNextRun = false;
  1091. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  1092. await setState({
  1093. autoRunSkipFailures,
  1094. ...getAutoRunStatusPayload('running', { currentRun: 0, totalRuns, attemptRun: 0 }),
  1095. });
  1096. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  1097. attemptRuns += 1;
  1098. const targetRun = successfulRuns + 1;
  1099. autoRunCurrentRun = targetRun;
  1100. autoRunAttemptRun = attemptRuns;
  1101. let startStep = 1;
  1102. let useExistingProgress = false;
  1103. if (continueCurrentOnFirstAttempt) {
  1104. const currentState = await getState();
  1105. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  1106. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  1107. startStep = resumeStep;
  1108. useExistingProgress = true;
  1109. } else if (hasSavedProgress(currentState.stepStatuses)) {
  1110. await addLog('当前流程已全部处理,将按“重新开始”新开一轮自动运行。', 'info');
  1111. }
  1112. continueCurrentOnFirstAttempt = false;
  1113. }
  1114. if (!useExistingProgress) {
  1115. // Reset everything at the start of each fresh attempt (keep user settings).
  1116. const prevState = await getState();
  1117. const keepSettings = {
  1118. vpsUrl: prevState.vpsUrl,
  1119. vpsPassword: prevState.vpsPassword,
  1120. customPassword: prevState.customPassword,
  1121. autoRunSkipFailures: prevState.autoRunSkipFailures,
  1122. mailProvider: prevState.mailProvider,
  1123. inbucketHost: prevState.inbucketHost,
  1124. inbucketMailbox: prevState.inbucketMailbox,
  1125. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  1126. ...(forceFreshTabsNextRun ? { tabRegistry: {} } : {}),
  1127. };
  1128. await resetState();
  1129. await setState(keepSettings);
  1130. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => {});
  1131. await sleepWithStop(500);
  1132. } else {
  1133. await setState({
  1134. autoRunSkipFailures,
  1135. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  1136. });
  1137. }
  1138. if (forceFreshTabsNextRun) {
  1139. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  1140. forceFreshTabsNextRun = false;
  1141. }
  1142. try {
  1143. throwIfStopped();
  1144. await broadcastAutoRunStatus('running', {
  1145. currentRun: targetRun,
  1146. totalRuns,
  1147. attemptRun: attemptRuns,
  1148. });
  1149. await runAutoSequenceFromStep(startStep, {
  1150. targetRun,
  1151. totalRuns,
  1152. attemptRuns,
  1153. continued: useExistingProgress,
  1154. });
  1155. successfulRuns += 1;
  1156. autoRunCurrentRun = successfulRuns;
  1157. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  1158. continue;
  1159. } catch (err) {
  1160. if (isStopError(err)) {
  1161. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  1162. await broadcastAutoRunStatus('stopped', {
  1163. currentRun: targetRun,
  1164. totalRuns,
  1165. attemptRun: attemptRuns,
  1166. });
  1167. break;
  1168. }
  1169. if (!autoRunSkipFailures) {
  1170. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  1171. await broadcastAutoRunStatus('stopped', {
  1172. currentRun: targetRun,
  1173. totalRuns,
  1174. attemptRun: attemptRuns,
  1175. });
  1176. break;
  1177. }
  1178. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  1179. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  1180. cancelPendingCommands('当前尝试已放弃。');
  1181. await broadcastStopToContentScripts();
  1182. await broadcastAutoRunStatus('retrying', {
  1183. currentRun: targetRun,
  1184. totalRuns,
  1185. attemptRun: attemptRuns,
  1186. });
  1187. forceFreshTabsNextRun = true;
  1188. }
  1189. }
  1190. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  1191. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  1192. await broadcastAutoRunStatus('stopped', {
  1193. currentRun: successfulRuns,
  1194. totalRuns: autoRunTotalRuns,
  1195. attemptRun: attemptRuns,
  1196. });
  1197. } else if (stopRequested) {
  1198. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1199. await broadcastAutoRunStatus('stopped', {
  1200. currentRun: successfulRuns,
  1201. totalRuns: autoRunTotalRuns,
  1202. attemptRun: attemptRuns,
  1203. });
  1204. } else if (successfulRuns >= autoRunTotalRuns) {
  1205. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  1206. await broadcastAutoRunStatus('complete', {
  1207. currentRun: successfulRuns,
  1208. totalRuns: autoRunTotalRuns,
  1209. attemptRun: attemptRuns,
  1210. });
  1211. } else {
  1212. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1213. await broadcastAutoRunStatus('stopped', {
  1214. currentRun: successfulRuns,
  1215. totalRuns: autoRunTotalRuns,
  1216. attemptRun: attemptRuns,
  1217. });
  1218. }
  1219. autoRunActive = false;
  1220. autoRunAttemptRun = attemptRuns;
  1221. await setState(getAutoRunStatusPayload(stopRequested ? 'stopped' : (successfulRuns >= autoRunTotalRuns ? 'complete' : 'stopped'), {
  1222. currentRun: successfulRuns,
  1223. totalRuns: autoRunTotalRuns,
  1224. attemptRun: attemptRuns,
  1225. }));
  1226. clearStopRequest();
  1227. }
  1228. async function waitForResume() {
  1229. throwIfStopped();
  1230. const state = await getState();
  1231. if (state.email) {
  1232. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  1233. return;
  1234. }
  1235. return new Promise((resolve, reject) => {
  1236. resumeWaiter = { resolve, reject };
  1237. });
  1238. }
  1239. async function resumeAutoRun() {
  1240. throwIfStopped();
  1241. const state = await getState();
  1242. if (!state.email) {
  1243. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  1244. return;
  1245. }
  1246. await resumeAutoRunIfWaitingForEmail({ silent: true });
  1247. }
  1248. // ============================================================
  1249. // Step 1: Get OAuth Link (via vps-panel.js)
  1250. // ============================================================
  1251. async function executeStep1(state) {
  1252. if (!state.vpsUrl) {
  1253. throw new Error('尚未配置 VPS 地址,请先在侧边栏填写。');
  1254. }
  1255. await addLog('步骤 1:正在打开 VPS 面板...');
  1256. await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  1257. inject: ['content/utils.js', 'content/vps-panel.js'],
  1258. reloadIfSameUrl: true,
  1259. });
  1260. await sendToContentScript('vps-panel', {
  1261. type: 'EXECUTE_STEP',
  1262. step: 1,
  1263. source: 'background',
  1264. payload: { vpsPassword: state.vpsPassword },
  1265. });
  1266. }
  1267. // ============================================================
  1268. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  1269. // ============================================================
  1270. async function executeStep2(state) {
  1271. if (!state.oauthUrl) {
  1272. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1273. }
  1274. await addLog('步骤 2:正在打开认证链接...');
  1275. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1276. await sendToContentScript('signup-page', {
  1277. type: 'EXECUTE_STEP',
  1278. step: 2,
  1279. source: 'background',
  1280. payload: {},
  1281. });
  1282. }
  1283. // ============================================================
  1284. // Step 3: Fill Email & Password (via signup-page.js)
  1285. // ============================================================
  1286. async function executeStep3(state) {
  1287. if (!state.email) {
  1288. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  1289. }
  1290. const password = state.customPassword || generatePassword();
  1291. await setPasswordState(password);
  1292. // Save account record
  1293. const accounts = state.accounts || [];
  1294. accounts.push({ email: state.email, password, createdAt: new Date().toISOString() });
  1295. await setState({ accounts });
  1296. await addLog(
  1297. `步骤 3:正在填写邮箱 ${state.email},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  1298. );
  1299. await sendToContentScript('signup-page', {
  1300. type: 'EXECUTE_STEP',
  1301. step: 3,
  1302. source: 'background',
  1303. payload: { email: state.email, password },
  1304. });
  1305. }
  1306. // ============================================================
  1307. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  1308. // ============================================================
  1309. function getMailConfig(state) {
  1310. const provider = state.mailProvider || 'qq';
  1311. if (provider === '163') {
  1312. 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 邮箱' };
  1313. }
  1314. if (provider === 'inbucket') {
  1315. const host = normalizeInbucketOrigin(state.inbucketHost);
  1316. const mailbox = (state.inbucketMailbox || '').trim();
  1317. if (!host) {
  1318. return { error: 'Inbucket 主机地址为空或无效。' };
  1319. }
  1320. if (!mailbox) {
  1321. return { error: 'Inbucket 邮箱名称为空。' };
  1322. }
  1323. return {
  1324. source: 'inbucket-mail',
  1325. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  1326. label: `Inbucket 邮箱(${mailbox})`,
  1327. navigateOnReuse: true,
  1328. inject: ['content/utils.js', 'content/inbucket-mail.js'],
  1329. injectSource: 'inbucket-mail',
  1330. };
  1331. }
  1332. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  1333. }
  1334. function normalizeInbucketOrigin(rawValue) {
  1335. const value = (rawValue || '').trim();
  1336. if (!value) return '';
  1337. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  1338. try {
  1339. const parsed = new URL(candidate);
  1340. return parsed.origin;
  1341. } catch {
  1342. return '';
  1343. }
  1344. }
  1345. function getVerificationCodeStateKey(step) {
  1346. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  1347. }
  1348. function getVerificationCodeLabel(step) {
  1349. return step === 4 ? '注册' : '登录';
  1350. }
  1351. function getVerificationPollPayload(step, state, overrides = {}) {
  1352. if (step === 4) {
  1353. return {
  1354. filterAfterTimestamp: state.flowStartTime || 0,
  1355. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  1356. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  1357. targetEmail: state.email,
  1358. maxAttempts: 5,
  1359. intervalMs: 3000,
  1360. ...overrides,
  1361. };
  1362. }
  1363. return {
  1364. filterAfterTimestamp: state.lastEmailTimestamp || state.flowStartTime || 0,
  1365. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  1366. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  1367. targetEmail: state.email,
  1368. maxAttempts: 5,
  1369. intervalMs: 3000,
  1370. ...overrides,
  1371. };
  1372. }
  1373. async function requestVerificationCodeResend(step) {
  1374. const signupTabId = await getTabId('signup-page');
  1375. if (!signupTabId) {
  1376. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  1377. }
  1378. await chrome.tabs.update(signupTabId, { active: true });
  1379. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  1380. const result = await sendToContentScript('signup-page', {
  1381. type: 'RESEND_VERIFICATION_CODE',
  1382. step,
  1383. source: 'background',
  1384. payload: {},
  1385. });
  1386. if (result && result.error) {
  1387. throw new Error(result.error);
  1388. }
  1389. return Date.now();
  1390. }
  1391. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  1392. const stateKey = getVerificationCodeStateKey(step);
  1393. const rejectedCodes = new Set();
  1394. if (state[stateKey]) {
  1395. rejectedCodes.add(state[stateKey]);
  1396. }
  1397. for (const code of (pollOverrides.excludeCodes || [])) {
  1398. if (code) rejectedCodes.add(code);
  1399. }
  1400. let lastError = null;
  1401. let filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  1402. const maxRounds = pollOverrides.maxRounds || 3;
  1403. for (let round = 1; round <= maxRounds; round++) {
  1404. if (round > 1) {
  1405. filterAfterTimestamp = await requestVerificationCodeResend(step);
  1406. }
  1407. const payload = getVerificationPollPayload(step, state, {
  1408. ...pollOverrides,
  1409. filterAfterTimestamp,
  1410. excludeCodes: [...rejectedCodes],
  1411. });
  1412. try {
  1413. const result = await sendToContentScript(mail.source, {
  1414. type: 'POLL_EMAIL',
  1415. step,
  1416. source: 'background',
  1417. payload,
  1418. });
  1419. if (result && result.error) {
  1420. throw new Error(result.error);
  1421. }
  1422. if (!result || !result.code) {
  1423. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  1424. }
  1425. if (rejectedCodes.has(result.code)) {
  1426. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  1427. }
  1428. return result;
  1429. } catch (err) {
  1430. lastError = err;
  1431. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  1432. if (round < maxRounds) {
  1433. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  1434. }
  1435. }
  1436. }
  1437. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  1438. }
  1439. async function submitVerificationCode(step, code) {
  1440. const signupTabId = await getTabId('signup-page');
  1441. if (!signupTabId) {
  1442. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  1443. }
  1444. await chrome.tabs.update(signupTabId, { active: true });
  1445. const result = await sendToContentScript('signup-page', {
  1446. type: 'FILL_CODE',
  1447. step,
  1448. source: 'background',
  1449. payload: { code },
  1450. });
  1451. if (result && result.error) {
  1452. throw new Error(result.error);
  1453. }
  1454. return result || {};
  1455. }
  1456. async function resolveVerificationStep(step, state, mail) {
  1457. const stateKey = getVerificationCodeStateKey(step);
  1458. const rejectedCodes = new Set();
  1459. if (state[stateKey]) {
  1460. rejectedCodes.add(state[stateKey]);
  1461. }
  1462. let nextFilterAfterTimestamp = null;
  1463. const maxSubmitAttempts = 3;
  1464. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  1465. const result = await pollFreshVerificationCode(step, state, mail, {
  1466. excludeCodes: [...rejectedCodes],
  1467. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  1468. });
  1469. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  1470. const submitResult = await submitVerificationCode(step, result.code);
  1471. if (submitResult.invalidCode) {
  1472. rejectedCodes.add(result.code);
  1473. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  1474. if (attempt >= maxSubmitAttempts) {
  1475. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  1476. }
  1477. nextFilterAfterTimestamp = await requestVerificationCodeResend(step);
  1478. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  1479. continue;
  1480. }
  1481. await setState({
  1482. lastEmailTimestamp: result.emailTimestamp,
  1483. [stateKey]: result.code,
  1484. });
  1485. await completeStepFromBackground(step, {
  1486. emailTimestamp: result.emailTimestamp,
  1487. code: result.code,
  1488. });
  1489. return;
  1490. }
  1491. }
  1492. async function executeStep4(state) {
  1493. const mail = getMailConfig(state);
  1494. if (mail.error) throw new Error(mail.error);
  1495. const signupTabId = await getTabId('signup-page');
  1496. if (!signupTabId) {
  1497. throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
  1498. }
  1499. await chrome.tabs.update(signupTabId, { active: true });
  1500. await addLog('步骤 4:正在确认注册验证码页面是否就绪,必要时自动恢复密码页超时报错...');
  1501. const prepareResult = await sendToContentScript('signup-page', {
  1502. type: 'PREPARE_SIGNUP_VERIFICATION',
  1503. step: 4,
  1504. source: 'background',
  1505. payload: { password: state.password || state.customPassword || '' },
  1506. });
  1507. if (prepareResult && prepareResult.error) {
  1508. throw new Error(prepareResult.error);
  1509. }
  1510. if (prepareResult?.alreadyVerified) {
  1511. await completeStepFromBackground(4, {});
  1512. return;
  1513. }
  1514. await addLog(`步骤 4:正在打开${mail.label}...`);
  1515. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  1516. const alive = await isTabAlive(mail.source);
  1517. if (alive) {
  1518. if (mail.navigateOnReuse) {
  1519. await reuseOrCreateTab(mail.source, mail.url, {
  1520. inject: mail.inject,
  1521. injectSource: mail.injectSource,
  1522. });
  1523. } else {
  1524. const tabId = await getTabId(mail.source);
  1525. await chrome.tabs.update(tabId, { active: true });
  1526. }
  1527. } else {
  1528. await reuseOrCreateTab(mail.source, mail.url, {
  1529. inject: mail.inject,
  1530. injectSource: mail.injectSource,
  1531. });
  1532. }
  1533. await resolveVerificationStep(4, state, mail);
  1534. return;
  1535. }
  1536. // ============================================================
  1537. // Step 5: Fill Name & Birthday (via signup-page.js)
  1538. // ============================================================
  1539. async function executeStep5(state) {
  1540. const { firstName, lastName } = generateRandomName();
  1541. const { year, month, day } = generateRandomBirthday();
  1542. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  1543. await sendToContentScript('signup-page', {
  1544. type: 'EXECUTE_STEP',
  1545. step: 5,
  1546. source: 'background',
  1547. payload: { firstName, lastName, year, month, day },
  1548. });
  1549. }
  1550. // ============================================================
  1551. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  1552. // ============================================================
  1553. async function refreshOAuthUrlBeforeStep6(state) {
  1554. if (!state.vpsUrl) {
  1555. throw new Error('尚未配置 VPS 地址,请先在侧边栏填写。');
  1556. }
  1557. await addLog('步骤 6:正在刷新登录用的 OAuth 链接...');
  1558. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  1559. await executeStep1(state);
  1560. await waitForFreshOAuth;
  1561. const latestState = await getState();
  1562. if (!latestState.oauthUrl) {
  1563. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  1564. }
  1565. return latestState.oauthUrl;
  1566. }
  1567. async function executeStep6(state) {
  1568. if (!state.email) {
  1569. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  1570. }
  1571. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  1572. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  1573. // Reuse the signup-page tab — navigate it to the OAuth URL
  1574. await reuseOrCreateTab('signup-page', oauthUrl);
  1575. // signup-page.js will inject (same auth.openai.com domain) and handle login
  1576. await sendToContentScript('signup-page', {
  1577. type: 'EXECUTE_STEP',
  1578. step: 6,
  1579. source: 'background',
  1580. payload: { email: state.email, password: state.password },
  1581. });
  1582. }
  1583. // ============================================================
  1584. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  1585. // ============================================================
  1586. async function executeStep7(state) {
  1587. const mail = getMailConfig(state);
  1588. if (mail.error) throw new Error(mail.error);
  1589. const authTabId = await getTabId('signup-page');
  1590. if (authTabId) {
  1591. await chrome.tabs.update(authTabId, { active: true });
  1592. } else {
  1593. if (!state.oauthUrl) {
  1594. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1595. }
  1596. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1597. }
  1598. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  1599. const prepareResult = await sendToContentScript('signup-page', {
  1600. type: 'PREPARE_LOGIN_CODE',
  1601. step: 7,
  1602. source: 'background',
  1603. payload: {},
  1604. });
  1605. if (prepareResult && prepareResult.error) {
  1606. throw new Error(prepareResult.error);
  1607. }
  1608. await addLog(`步骤 7:正在打开${mail.label}...`);
  1609. const alive = await isTabAlive(mail.source);
  1610. if (alive) {
  1611. if (mail.navigateOnReuse) {
  1612. await reuseOrCreateTab(mail.source, mail.url, {
  1613. inject: mail.inject,
  1614. injectSource: mail.injectSource,
  1615. });
  1616. } else {
  1617. const tabId = await getTabId(mail.source);
  1618. await chrome.tabs.update(tabId, { active: true });
  1619. }
  1620. } else {
  1621. await reuseOrCreateTab(mail.source, mail.url, {
  1622. inject: mail.inject,
  1623. injectSource: mail.injectSource,
  1624. });
  1625. }
  1626. await resolveVerificationStep(7, state, mail);
  1627. return;
  1628. }
  1629. // ============================================================
  1630. // Step 8: Complete OAuth (auto click + localhost listener)
  1631. // ============================================================
  1632. let webNavListener = null;
  1633. async function executeStep8(state) {
  1634. if (!state.oauthUrl) {
  1635. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1636. }
  1637. await addLog('步骤 8:正在监听 localhost 回调地址...');
  1638. // Register webNavigation listener (scoped to this step)
  1639. return new Promise((resolve, reject) => {
  1640. let resolved = false;
  1641. let resolveCaptureWait = null;
  1642. const captureWait = new Promise((resolveCapture) => {
  1643. resolveCaptureWait = resolveCapture;
  1644. });
  1645. const cleanupListener = () => {
  1646. if (webNavListener) {
  1647. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  1648. webNavListener = null;
  1649. }
  1650. };
  1651. const timeout = setTimeout(() => {
  1652. cleanupListener();
  1653. reject(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  1654. }, 120000);
  1655. webNavListener = (details) => {
  1656. if (details.url.startsWith('http://localhost')) {
  1657. console.log(LOG_PREFIX, `Captured localhost redirect: ${details.url}`);
  1658. resolved = true;
  1659. cleanupListener();
  1660. clearTimeout(timeout);
  1661. if (resolveCaptureWait) resolveCaptureWait(details.url);
  1662. setState({ localhostUrl: details.url }).then(() => {
  1663. addLog(`步骤 8:已捕获 localhost 地址:${details.url}`, 'ok');
  1664. setStepStatus(8, 'completed');
  1665. notifyStepComplete(8, { localhostUrl: details.url });
  1666. broadcastDataUpdate({ localhostUrl: details.url });
  1667. resolve();
  1668. });
  1669. }
  1670. };
  1671. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  1672. // After step 7, the auth page shows a consent screen ("使用 ChatGPT 登录到 Codex")
  1673. // with a "继续" button. We locate the button in-page, then click it through
  1674. // the debugger Input API directly.
  1675. (async () => {
  1676. try {
  1677. let signupTabId = await getTabId('signup-page');
  1678. if (signupTabId) {
  1679. await chrome.tabs.update(signupTabId, { active: true });
  1680. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  1681. } else {
  1682. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  1683. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  1684. }
  1685. const clickResult = await sendToContentScript('signup-page', {
  1686. type: 'STEP8_FIND_AND_CLICK',
  1687. source: 'background',
  1688. payload: {},
  1689. });
  1690. if (clickResult?.error) {
  1691. throw new Error(clickResult.error);
  1692. }
  1693. if (!resolved) {
  1694. await clickWithDebugger(signupTabId, clickResult?.rect);
  1695. await addLog('步骤 8:已发送调试器点击,正在等待跳转...');
  1696. }
  1697. } catch (err) {
  1698. clearTimeout(timeout);
  1699. cleanupListener();
  1700. reject(err);
  1701. }
  1702. })();
  1703. });
  1704. }
  1705. // ============================================================
  1706. // Step 9: VPS Verify (via vps-panel.js)
  1707. // ============================================================
  1708. async function executeStep9(state) {
  1709. if (!state.localhostUrl) {
  1710. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  1711. }
  1712. if (!state.vpsUrl) {
  1713. throw new Error('尚未填写 VPS 地址,请先在侧边栏输入。');
  1714. }
  1715. await addLog('步骤 9:正在打开 VPS 面板...');
  1716. let tabId = await getTabId('vps-panel');
  1717. const alive = tabId && await isTabAlive('vps-panel');
  1718. if (!alive) {
  1719. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  1720. // Create new tab
  1721. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  1722. tabId = tab.id;
  1723. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  1724. await new Promise(resolve => {
  1725. const listener = (tid, info) => {
  1726. if (tid === tabId && info.status === 'complete') {
  1727. chrome.tabs.onUpdated.removeListener(listener);
  1728. resolve();
  1729. }
  1730. };
  1731. chrome.tabs.onUpdated.addListener(listener);
  1732. });
  1733. } else {
  1734. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  1735. await chrome.tabs.update(tabId, { active: true });
  1736. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  1737. }
  1738. // Inject scripts directly and wait for them to be ready
  1739. await chrome.scripting.executeScript({
  1740. target: { tabId },
  1741. files: ['content/utils.js', 'content/vps-panel.js'],
  1742. });
  1743. await new Promise(r => setTimeout(r, 1000));
  1744. // Send command directly — bypass queue/ready mechanism
  1745. await addLog('步骤 9:正在填写回调地址...');
  1746. await chrome.tabs.sendMessage(tabId, {
  1747. type: 'EXECUTE_STEP',
  1748. step: 9,
  1749. source: 'background',
  1750. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  1751. });
  1752. }
  1753. // ============================================================
  1754. // Open Side Panel on extension icon click
  1755. // ============================================================
  1756. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });