background.js 71 KB

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