background.js 76 KB

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