background.js 81 KB

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