background.js 66 KB

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