background.js 93 KB

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