background.js 82 KB

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