background.js 75 KB

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