background.js 67 KB

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