background.js 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331
  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. const AUTO_RUN_ALARM_NAME = 'scheduled-auto-run';
  10. const AUTO_RUN_DELAY_MIN_MINUTES = 1;
  11. const AUTO_RUN_DELAY_MAX_MINUTES = 1440;
  12. initializeSessionStorageAccess();
  13. // ============================================================
  14. // 状态管理(chrome.storage.session + chrome.storage.local)
  15. // ============================================================
  16. const PERSISTED_SETTING_DEFAULTS = {
  17. vpsUrl: '', // VPS 面板地址,可手动填写。
  18. vpsPassword: '', // VPS 面板登录密码,可手动填写。
  19. customPassword: '', // 自定义账号密码;留空时由程序自动生成随机密码。
  20. autoRunSkipFailures: false, // 自动运行遇到失败步骤后,是否继续执行后续流程。
  21. autoRunDelayEnabled: false, // 自动运行是否启用启动前倒计时。
  22. autoRunDelayMinutes: 30, // 自动运行倒计时分钟数。
  23. mailProvider: '163', // 验证码邮箱来源,当前支持 163 / inbucket。
  24. inbucketHost: '', // 仅当 mailProvider 为 inbucket 时填写 Inbucket 地址,其他情况保持为空。
  25. inbucketMailbox: '', // 仅当 mailProvider 为 inbucket 时填写邮箱名,其他情况保持为空。
  26. };
  27. const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);
  28. const DEFAULT_STATE = {
  29. currentStep: 0, // 当前流程执行到的步骤编号。
  30. stepStatuses: {
  31. 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending', // 运行时步骤状态映射,不要手动预填。
  32. 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
  33. },
  34. oauthUrl: null, // 运行时抓取到的 OAuth 地址,不要手动预填。
  35. email: null, // 运行时邮箱,由程序自动获取并写入,不能手动预填。
  36. password: null, // 运行时实际密码,由 customPassword 或程序自动生成后写入。
  37. accounts: [], // 已生成账号记录:{ email, password, createdAt }。
  38. lastEmailTimestamp: null, // 最近一次获取到邮箱数据的运行时时间戳。
  39. lastSignupCode: null, // 注册验证码,运行时由程序自动读取并写入。
  40. lastLoginCode: null, // 登录验证码,运行时由程序自动读取并写入。
  41. localhostUrl: null, // 运行时捕获到的 localhost 回调地址,不要手动预填。
  42. flowStartTime: null, // 当前流程开始时间。
  43. tabRegistry: {}, // 程序维护的标签页注册表。
  44. sourceLastUrls: {}, // 各来源页面最近一次打开的地址记录。
  45. logs: [], // 侧边栏展示的运行日志。
  46. ...PERSISTED_SETTING_DEFAULTS, // 合并 chrome.storage.local 中持久化保存的用户配置。
  47. autoRunning: false, // 当前是否处于自动运行中。
  48. autoRunPhase: 'idle', // 当前自动运行阶段。
  49. autoRunCurrentRun: 0, // 自动运行当前执行到第几轮。
  50. autoRunTotalRuns: 1, // 自动运行计划总轮数。
  51. autoRunAttemptRun: 0, // 当前轮次的重试序号。
  52. scheduledAutoRunAt: null, // 自动运行计划启动时间戳。
  53. scheduledAutoRunPlan: null, // 自动运行计划参数快照。
  54. };
  55. function normalizeAutoRunDelayMinutes(value) {
  56. const numeric = Number(value);
  57. if (!Number.isFinite(numeric)) {
  58. return PERSISTED_SETTING_DEFAULTS.autoRunDelayMinutes;
  59. }
  60. return Math.min(
  61. AUTO_RUN_DELAY_MAX_MINUTES,
  62. Math.max(AUTO_RUN_DELAY_MIN_MINUTES, Math.floor(numeric))
  63. );
  64. }
  65. function normalizeRunCount(value) {
  66. const numeric = Number(value);
  67. if (!Number.isFinite(numeric)) {
  68. return 1;
  69. }
  70. return Math.min(50, Math.max(1, Math.floor(numeric)));
  71. }
  72. function normalizeScheduledAutoRunPlan(plan) {
  73. if (!plan || typeof plan !== 'object') {
  74. return null;
  75. }
  76. return {
  77. totalRuns: normalizeRunCount(plan.totalRuns),
  78. autoRunSkipFailures: Boolean(plan.autoRunSkipFailures),
  79. mode: plan.mode === 'continue' ? 'continue' : 'restart',
  80. };
  81. }
  82. async function getPersistedSettings() {
  83. const stored = await chrome.storage.local.get(PERSISTED_SETTING_KEYS);
  84. return {
  85. ...PERSISTED_SETTING_DEFAULTS,
  86. ...stored,
  87. autoRunSkipFailures: Boolean(stored.autoRunSkipFailures ?? PERSISTED_SETTING_DEFAULTS.autoRunSkipFailures),
  88. autoRunDelayEnabled: Boolean(stored.autoRunDelayEnabled ?? PERSISTED_SETTING_DEFAULTS.autoRunDelayEnabled),
  89. autoRunDelayMinutes: normalizeAutoRunDelayMinutes(stored.autoRunDelayMinutes ?? PERSISTED_SETTING_DEFAULTS.autoRunDelayMinutes),
  90. };
  91. }
  92. async function getState() {
  93. const [state, persistedSettings] = await Promise.all([
  94. chrome.storage.session.get(null),
  95. getPersistedSettings(),
  96. ]);
  97. return { ...DEFAULT_STATE, ...persistedSettings, ...state };
  98. }
  99. async function initializeSessionStorageAccess() {
  100. try {
  101. if (chrome.storage?.session?.setAccessLevel) {
  102. await chrome.storage.session.setAccessLevel({
  103. accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS',
  104. });
  105. console.log(LOG_PREFIX, 'Enabled storage.session for content scripts');
  106. }
  107. } catch (err) {
  108. console.warn(LOG_PREFIX, 'Failed to enable storage.session for content scripts:', err?.message || err);
  109. }
  110. }
  111. async function setState(updates) {
  112. console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
  113. await chrome.storage.session.set(updates);
  114. }
  115. async function setPersistentSettings(updates) {
  116. const persistedUpdates = {};
  117. for (const key of PERSISTED_SETTING_KEYS) {
  118. if (updates[key] !== undefined) {
  119. if (key === 'autoRunSkipFailures' || key === 'autoRunDelayEnabled') {
  120. persistedUpdates[key] = Boolean(updates[key]);
  121. } else if (key === 'autoRunDelayMinutes') {
  122. persistedUpdates[key] = normalizeAutoRunDelayMinutes(updates[key]);
  123. } else {
  124. persistedUpdates[key] = updates[key];
  125. }
  126. }
  127. }
  128. if (Object.keys(persistedUpdates).length > 0) {
  129. await chrome.storage.local.set(persistedUpdates);
  130. }
  131. }
  132. function broadcastDataUpdate(payload) {
  133. chrome.runtime.sendMessage({
  134. type: 'DATA_UPDATED',
  135. payload,
  136. }).catch(() => { });
  137. }
  138. async function setEmailState(email) {
  139. await setState({ email });
  140. broadcastDataUpdate({ email });
  141. if (email) {
  142. await resumeAutoRunIfWaitingForEmail();
  143. }
  144. }
  145. async function setPasswordState(password) {
  146. await setState({ password });
  147. broadcastDataUpdate({ password });
  148. }
  149. async function resetState() {
  150. console.log(LOG_PREFIX, 'Resetting all state');
  151. // Preserve settings and persistent data across resets
  152. const [prev, persistedSettings] = await Promise.all([
  153. chrome.storage.session.get([
  154. 'seenCodes',
  155. 'seenInbucketMailIds',
  156. 'accounts',
  157. 'tabRegistry',
  158. 'sourceLastUrls',
  159. ]),
  160. getPersistedSettings(),
  161. ]);
  162. await chrome.storage.session.clear();
  163. await chrome.storage.session.set({
  164. ...DEFAULT_STATE,
  165. ...persistedSettings,
  166. seenCodes: prev.seenCodes || [],
  167. seenInbucketMailIds: prev.seenInbucketMailIds || [],
  168. accounts: prev.accounts || [],
  169. tabRegistry: prev.tabRegistry || {},
  170. sourceLastUrls: prev.sourceLastUrls || {},
  171. });
  172. }
  173. /**
  174. * Generate a random password: 14 chars, mix of uppercase, lowercase, digits, symbols.
  175. */
  176. function generatePassword() {
  177. const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  178. const lower = 'abcdefghjkmnpqrstuvwxyz';
  179. const digits = '23456789';
  180. const symbols = '!@#$%&*?';
  181. const all = upper + lower + digits + symbols;
  182. // Ensure at least one of each type
  183. let pw = '';
  184. pw += upper[Math.floor(Math.random() * upper.length)];
  185. pw += lower[Math.floor(Math.random() * lower.length)];
  186. pw += digits[Math.floor(Math.random() * digits.length)];
  187. pw += symbols[Math.floor(Math.random() * symbols.length)];
  188. // Fill remaining 10 chars
  189. for (let i = 0; i < 10; i++) {
  190. pw += all[Math.floor(Math.random() * all.length)];
  191. }
  192. // Shuffle
  193. return pw.split('').sort(() => Math.random() - 0.5).join('');
  194. }
  195. // ============================================================
  196. // Tab Registry
  197. // ============================================================
  198. async function getTabRegistry() {
  199. const state = await getState();
  200. return state.tabRegistry || {};
  201. }
  202. async function registerTab(source, tabId) {
  203. const registry = await getTabRegistry();
  204. registry[source] = { tabId, ready: true };
  205. await setState({ tabRegistry: registry });
  206. console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
  207. }
  208. async function isTabAlive(source) {
  209. const registry = await getTabRegistry();
  210. const entry = registry[source];
  211. if (!entry) return false;
  212. try {
  213. await chrome.tabs.get(entry.tabId);
  214. return true;
  215. } catch {
  216. // Tab no longer exists — clean up registry
  217. registry[source] = null;
  218. await setState({ tabRegistry: registry });
  219. return false;
  220. }
  221. }
  222. async function getTabId(source) {
  223. const registry = await getTabRegistry();
  224. return registry[source]?.tabId || null;
  225. }
  226. function parseUrlSafely(rawUrl) {
  227. if (!rawUrl) return null;
  228. try {
  229. return new URL(rawUrl);
  230. } catch {
  231. return null;
  232. }
  233. }
  234. function isSignupPageHost(hostname = '') {
  235. return ['auth0.openai.com', 'auth.openai.com', 'accounts.openai.com'].includes(hostname);
  236. }
  237. function is163MailHost(hostname = '') {
  238. return hostname === 'mail.163.com'
  239. || hostname.endsWith('.mail.163.com')
  240. || hostname === 'webmail.vip.163.com';
  241. }
  242. function isLocalhostOAuthCallbackUrl(rawUrl) {
  243. const parsed = parseUrlSafely(rawUrl);
  244. if (!parsed) return false;
  245. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  246. if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
  247. if (!['/auth/callback', '/codex/callback'].includes(parsed.pathname)) return false;
  248. const code = (parsed.searchParams.get('code') || '').trim();
  249. const state = (parsed.searchParams.get('state') || '').trim();
  250. return Boolean(code && state);
  251. }
  252. function isLocalCpaUrl(rawUrl) {
  253. const parsed = parseUrlSafely(rawUrl);
  254. if (!parsed) return false;
  255. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  256. return ['localhost', '127.0.0.1'].includes(parsed.hostname);
  257. }
  258. function shouldBypassStep9ForLocalCpa(state) {
  259. return Boolean(state?.localhostUrl) && isLocalCpaUrl(state?.vpsUrl);
  260. }
  261. function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
  262. const candidate = parseUrlSafely(candidateUrl);
  263. if (!candidate) return false;
  264. const reference = parseUrlSafely(referenceUrl);
  265. switch (source) {
  266. case 'signup-page':
  267. return isSignupPageHost(candidate.hostname);
  268. case 'duck-mail':
  269. return candidate.hostname === 'duckduckgo.com' && candidate.pathname.startsWith('/email/');
  270. case 'qq-mail':
  271. return candidate.hostname === 'mail.qq.com' || candidate.hostname === 'wx.mail.qq.com';
  272. case 'mail-163':
  273. return is163MailHost(candidate.hostname);
  274. case 'inbucket-mail':
  275. return Boolean(reference)
  276. && candidate.origin === reference.origin
  277. && candidate.pathname.startsWith('/m/');
  278. case 'vps-panel':
  279. return Boolean(reference)
  280. && candidate.origin === reference.origin
  281. && candidate.pathname === reference.pathname;
  282. default:
  283. return false;
  284. }
  285. }
  286. async function rememberSourceLastUrl(source, url) {
  287. if (!source || !url) return;
  288. const state = await getState();
  289. const sourceLastUrls = { ...(state.sourceLastUrls || {}) };
  290. sourceLastUrls[source] = url;
  291. await setState({ sourceLastUrls });
  292. }
  293. async function closeConflictingTabsForSource(source, currentUrl, options = {}) {
  294. const { excludeTabIds = [] } = options;
  295. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  296. const state = await getState();
  297. const lastUrl = state.sourceLastUrls?.[source];
  298. const referenceUrls = [currentUrl, lastUrl].filter(Boolean);
  299. if (!referenceUrls.length) return;
  300. const tabs = await chrome.tabs.query({});
  301. const matchedIds = tabs
  302. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  303. .filter((tab) => referenceUrls.some((refUrl) => matchesSourceUrlFamily(source, tab.url, refUrl)))
  304. .map(tab => tab.id);
  305. if (!matchedIds.length) return;
  306. await chrome.tabs.remove(matchedIds).catch(() => { });
  307. const registry = await getTabRegistry();
  308. if (registry[source]?.tabId && matchedIds.includes(registry[source].tabId)) {
  309. registry[source] = null;
  310. await setState({ tabRegistry: registry });
  311. }
  312. await addLog(`已关闭 ${matchedIds.length} 个旧的${getSourceLabel(source)}标签页。`, 'info');
  313. }
  314. function isLocalhostOAuthCallbackTabMatch(callbackUrl, candidateUrl) {
  315. if (!isLocalhostOAuthCallbackUrl(callbackUrl) || !isLocalhostOAuthCallbackUrl(candidateUrl)) {
  316. return false;
  317. }
  318. const callback = parseUrlSafely(callbackUrl);
  319. const candidate = parseUrlSafely(candidateUrl);
  320. if (!callback || !candidate) return false;
  321. return callback.origin === candidate.origin
  322. && callback.pathname === candidate.pathname
  323. && callback.searchParams.get('code') === candidate.searchParams.get('code')
  324. && callback.searchParams.get('state') === candidate.searchParams.get('state');
  325. }
  326. async function closeLocalhostCallbackTabs(callbackUrl, options = {}) {
  327. if (!isLocalhostOAuthCallbackUrl(callbackUrl)) return 0;
  328. const { excludeTabIds = [] } = options;
  329. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  330. const tabs = await chrome.tabs.query({});
  331. const matchedIds = tabs
  332. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  333. .filter((tab) => isLocalhostOAuthCallbackTabMatch(callbackUrl, tab.url))
  334. .map((tab) => tab.id);
  335. if (!matchedIds.length) return 0;
  336. await chrome.tabs.remove(matchedIds).catch(() => { });
  337. const registry = await getTabRegistry();
  338. if (registry['signup-page']?.tabId && matchedIds.includes(registry['signup-page'].tabId)) {
  339. registry['signup-page'] = null;
  340. await setState({ tabRegistry: registry });
  341. }
  342. await addLog(`已关闭 ${matchedIds.length} 个匹配当前 OAuth callback 的 localhost 残留标签页。`, 'info');
  343. return matchedIds.length;
  344. }
  345. async function pingContentScriptOnTab(tabId) {
  346. if (!Number.isInteger(tabId)) return null;
  347. try {
  348. return await chrome.tabs.sendMessage(tabId, {
  349. type: 'PING',
  350. source: 'background',
  351. payload: {},
  352. });
  353. } catch {
  354. return null;
  355. }
  356. }
  357. async function waitForTabUrlFamily(source, tabId, referenceUrl, options = {}) {
  358. const { timeoutMs = 15000, retryDelayMs = 400 } = options;
  359. const start = Date.now();
  360. while (Date.now() - start < timeoutMs) {
  361. try {
  362. const tab = await chrome.tabs.get(tabId);
  363. if (matchesSourceUrlFamily(source, tab.url, referenceUrl)) {
  364. return tab;
  365. }
  366. } catch {
  367. return null;
  368. }
  369. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  370. }
  371. return null;
  372. }
  373. async function ensureContentScriptReadyOnTab(source, tabId, options = {}) {
  374. const {
  375. inject = null,
  376. injectSource = null,
  377. timeoutMs = 30000,
  378. retryDelayMs = 700,
  379. logMessage = '',
  380. } = options;
  381. const start = Date.now();
  382. let lastError = null;
  383. let logged = false;
  384. let attempt = 0;
  385. console.log(
  386. LOG_PREFIX,
  387. `[ensureContentScriptReadyOnTab] start ${source} tab=${tabId}, timeout=${timeoutMs}ms, inject=${Array.isArray(inject) ? inject.join(',') : 'none'}`
  388. );
  389. while (Date.now() - start < timeoutMs) {
  390. attempt += 1;
  391. const pong = await pingContentScriptOnTab(tabId);
  392. if (pong?.ok && (!pong.source || pong.source === source)) {
  393. console.log(
  394. LOG_PREFIX,
  395. `[ensureContentScriptReadyOnTab] ready ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  396. );
  397. await registerTab(source, tabId);
  398. return;
  399. }
  400. if (!inject || !inject.length) {
  401. throw new Error(`${getSourceLabel(source)} 内容脚本未就绪,且未提供可用的注入文件。`);
  402. }
  403. const registry = await getTabRegistry();
  404. if (registry[source]) {
  405. registry[source].ready = false;
  406. await setState({ tabRegistry: registry });
  407. }
  408. try {
  409. if (injectSource) {
  410. await chrome.scripting.executeScript({
  411. target: { tabId },
  412. func: (injectedSource) => {
  413. window.__MULTIPAGE_SOURCE = injectedSource;
  414. },
  415. args: [injectSource],
  416. });
  417. }
  418. await chrome.scripting.executeScript({
  419. target: { tabId },
  420. files: inject,
  421. });
  422. } catch (err) {
  423. lastError = err;
  424. console.warn(
  425. LOG_PREFIX,
  426. `[ensureContentScriptReadyOnTab] inject attempt ${attempt} failed for ${source} tab=${tabId}: ${err?.message || err}`
  427. );
  428. }
  429. const pongAfterInject = await pingContentScriptOnTab(tabId);
  430. if (pongAfterInject?.ok && (!pongAfterInject.source || pongAfterInject.source === source)) {
  431. console.log(
  432. LOG_PREFIX,
  433. `[ensureContentScriptReadyOnTab] ready after inject ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  434. );
  435. await registerTab(source, tabId);
  436. return;
  437. }
  438. if (logMessage && !logged) {
  439. console.warn(
  440. LOG_PREFIX,
  441. `[ensureContentScriptReadyOnTab] ${source} tab=${tabId} still not ready after ${Date.now() - start}ms`
  442. );
  443. await addLog(logMessage, 'warn');
  444. logged = true;
  445. }
  446. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  447. }
  448. throw lastError || new Error(`${getSourceLabel(source)} 内容脚本长时间未就绪。`);
  449. }
  450. // ============================================================
  451. // Command Queue (for content scripts not yet ready)
  452. // ============================================================
  453. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  454. function getContentScriptResponseTimeoutMs(message) {
  455. if (!message || typeof message !== 'object') {
  456. return 30000;
  457. }
  458. if (message.type === 'POLL_EMAIL') {
  459. const maxAttempts = Math.max(1, Number(message.payload?.maxAttempts) || 1);
  460. const intervalMs = Math.max(0, Number(message.payload?.intervalMs) || 0);
  461. return Math.max(45000, maxAttempts * intervalMs + 25000);
  462. }
  463. if (message.type === 'FILL_CODE') {
  464. return Number(message.step) === 7 ? 45000 : 30000;
  465. }
  466. if (message.type === 'PREPARE_SIGNUP_VERIFICATION') {
  467. return 45000;
  468. }
  469. return 30000;
  470. }
  471. function getMessageDebugLabel(source, message, tabId = null) {
  472. const parts = [source || 'unknown', message?.type || 'UNKNOWN'];
  473. if (Number.isInteger(message?.step)) {
  474. parts.push(`step=${message.step}`);
  475. }
  476. if (Number.isInteger(tabId)) {
  477. parts.push(`tab=${tabId}`);
  478. }
  479. return parts.join(' ');
  480. }
  481. function summarizeMessageResultForDebug(result) {
  482. if (result === undefined) return 'undefined';
  483. if (result === null) return 'null';
  484. if (typeof result !== 'object') return JSON.stringify(result);
  485. const summary = {};
  486. for (const key of ['ok', 'error', 'stopped', 'source', 'step']) {
  487. if (key in result) summary[key] = result[key];
  488. }
  489. if (result.payload && typeof result.payload === 'object') {
  490. summary.payloadKeys = Object.keys(result.payload);
  491. }
  492. return JSON.stringify(summary);
  493. }
  494. function sendTabMessageWithTimeout(tabId, source, message, responseTimeoutMs = getContentScriptResponseTimeoutMs(message)) {
  495. return new Promise((resolve, reject) => {
  496. let settled = false;
  497. const startedAt = Date.now();
  498. const debugLabel = getMessageDebugLabel(source, message, tabId);
  499. console.log(LOG_PREFIX, `[sendTabMessageWithTimeout] dispatch ${debugLabel}, timeout=${responseTimeoutMs}ms`);
  500. const timer = setTimeout(() => {
  501. if (settled) return;
  502. settled = true;
  503. const seconds = Math.ceil(responseTimeoutMs / 1000);
  504. console.warn(LOG_PREFIX, `[sendTabMessageWithTimeout] timeout ${debugLabel} after ${Date.now() - startedAt}ms`);
  505. reject(new Error(`Content script on ${source} did not respond in ${seconds}s. Try refreshing the tab and retry.`));
  506. }, responseTimeoutMs);
  507. chrome.tabs.sendMessage(tabId, message)
  508. .then((value) => {
  509. const elapsed = Date.now() - startedAt;
  510. if (settled) {
  511. console.warn(
  512. LOG_PREFIX,
  513. `[sendTabMessageWithTimeout] late response ignored for ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  514. );
  515. return;
  516. }
  517. settled = true;
  518. clearTimeout(timer);
  519. console.log(
  520. LOG_PREFIX,
  521. `[sendTabMessageWithTimeout] response ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  522. );
  523. resolve(value);
  524. })
  525. .catch((error) => {
  526. const elapsed = Date.now() - startedAt;
  527. const errorMessage = error?.message || String(error);
  528. if (settled) {
  529. console.warn(
  530. LOG_PREFIX,
  531. `[sendTabMessageWithTimeout] late rejection ignored for ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  532. );
  533. return;
  534. }
  535. settled = true;
  536. clearTimeout(timer);
  537. console.warn(
  538. LOG_PREFIX,
  539. `[sendTabMessageWithTimeout] rejection ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  540. );
  541. reject(error);
  542. });
  543. });
  544. }
  545. function queueCommand(source, message, timeout = 15000) {
  546. return new Promise((resolve, reject) => {
  547. const timer = setTimeout(() => {
  548. pendingCommands.delete(source);
  549. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  550. console.error(LOG_PREFIX, err);
  551. reject(new Error(err));
  552. }, timeout);
  553. pendingCommands.set(source, { message, resolve, reject, timer });
  554. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  555. });
  556. }
  557. function flushCommand(source, tabId) {
  558. const pending = pendingCommands.get(source);
  559. if (pending) {
  560. clearTimeout(pending.timer);
  561. pendingCommands.delete(source);
  562. sendTabMessageWithTimeout(tabId, source, pending.message).then(pending.resolve).catch(pending.reject);
  563. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  564. }
  565. }
  566. function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
  567. for (const [source, pending] of pendingCommands.entries()) {
  568. clearTimeout(pending.timer);
  569. pending.reject(new Error(reason));
  570. pendingCommands.delete(source);
  571. console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
  572. }
  573. }
  574. // ============================================================
  575. // Reuse or create tab
  576. // ============================================================
  577. async function reuseOrCreateTab(source, url, options = {}) {
  578. const alive = await isTabAlive(source);
  579. if (alive) {
  580. const tabId = await getTabId(source);
  581. await closeConflictingTabsForSource(source, url, { excludeTabIds: [tabId] });
  582. const currentTab = await chrome.tabs.get(tabId);
  583. const sameUrl = currentTab.url === url;
  584. const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
  585. const registry = await getTabRegistry();
  586. if (sameUrl) {
  587. await chrome.tabs.update(tabId, { active: true });
  588. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
  589. if (shouldReloadOnReuse) {
  590. if (registry[source]) registry[source].ready = false;
  591. await setState({ tabRegistry: registry });
  592. await chrome.tabs.reload(tabId);
  593. await new Promise((resolve) => {
  594. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  595. const listener = (tid, info) => {
  596. if (tid === tabId && info.status === 'complete') {
  597. chrome.tabs.onUpdated.removeListener(listener);
  598. clearTimeout(timer);
  599. resolve();
  600. }
  601. };
  602. chrome.tabs.onUpdated.addListener(listener);
  603. });
  604. }
  605. // For dynamically injected pages like the VPS panel, re-inject immediately.
  606. if (options.inject) {
  607. if (registry[source]) registry[source].ready = false;
  608. await setState({ tabRegistry: registry });
  609. if (options.injectSource) {
  610. await chrome.scripting.executeScript({
  611. target: { tabId },
  612. func: (injectedSource) => {
  613. window.__MULTIPAGE_SOURCE = injectedSource;
  614. },
  615. args: [options.injectSource],
  616. });
  617. }
  618. await chrome.scripting.executeScript({
  619. target: { tabId },
  620. files: options.inject,
  621. });
  622. await new Promise(r => setTimeout(r, 500));
  623. }
  624. await rememberSourceLastUrl(source, url);
  625. return tabId;
  626. }
  627. // Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
  628. if (registry[source]) registry[source].ready = false;
  629. await setState({ tabRegistry: registry });
  630. // Navigate existing tab to new URL
  631. await chrome.tabs.update(tabId, { url, active: true });
  632. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
  633. // Wait for page load complete (with 30s timeout)
  634. await new Promise((resolve) => {
  635. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  636. const listener = (tid, info) => {
  637. if (tid === tabId && info.status === 'complete') {
  638. chrome.tabs.onUpdated.removeListener(listener);
  639. clearTimeout(timer);
  640. resolve();
  641. }
  642. };
  643. chrome.tabs.onUpdated.addListener(listener);
  644. });
  645. // If dynamic injection needed (VPS panel), re-inject after navigation
  646. if (options.inject) {
  647. if (options.injectSource) {
  648. await chrome.scripting.executeScript({
  649. target: { tabId },
  650. func: (injectedSource) => {
  651. window.__MULTIPAGE_SOURCE = injectedSource;
  652. },
  653. args: [options.injectSource],
  654. });
  655. }
  656. await chrome.scripting.executeScript({
  657. target: { tabId },
  658. files: options.inject,
  659. });
  660. }
  661. // Wait a bit for content script to inject and send READY
  662. await new Promise(r => setTimeout(r, 500));
  663. await rememberSourceLastUrl(source, url);
  664. return tabId;
  665. }
  666. // Create new tab
  667. await closeConflictingTabsForSource(source, url);
  668. const tab = await chrome.tabs.create({ url, active: true });
  669. console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
  670. // If dynamic injection needed (VPS panel), inject scripts after load
  671. if (options.inject) {
  672. await new Promise((resolve) => {
  673. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  674. const listener = (tabId, info) => {
  675. if (tabId === tab.id && info.status === 'complete') {
  676. chrome.tabs.onUpdated.removeListener(listener);
  677. clearTimeout(timer);
  678. resolve();
  679. }
  680. };
  681. chrome.tabs.onUpdated.addListener(listener);
  682. });
  683. if (options.injectSource) {
  684. await chrome.scripting.executeScript({
  685. target: { tabId: tab.id },
  686. func: (injectedSource) => {
  687. window.__MULTIPAGE_SOURCE = injectedSource;
  688. },
  689. args: [options.injectSource],
  690. });
  691. }
  692. await chrome.scripting.executeScript({
  693. target: { tabId: tab.id },
  694. files: options.inject,
  695. });
  696. }
  697. await rememberSourceLastUrl(source, url);
  698. return tab.id;
  699. }
  700. // ============================================================
  701. // Send command to content script (with readiness check)
  702. // ============================================================
  703. async function sendToContentScript(source, message, options = {}) {
  704. const { responseTimeoutMs = getContentScriptResponseTimeoutMs(message) } = options;
  705. const registry = await getTabRegistry();
  706. const entry = registry[source];
  707. if (!entry || !entry.ready) {
  708. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  709. return queueCommand(source, message);
  710. }
  711. // Verify tab is still alive
  712. const alive = await isTabAlive(source);
  713. if (!alive) {
  714. // Tab was closed — queue the command, it will be sent when tab is reopened
  715. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  716. return queueCommand(source, message);
  717. }
  718. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  719. return sendTabMessageWithTimeout(entry.tabId, source, message, responseTimeoutMs);
  720. }
  721. async function sendToContentScriptResilient(source, message, options = {}) {
  722. const { timeoutMs = 30000, retryDelayMs = 600, logMessage = '' } = options;
  723. const start = Date.now();
  724. let lastError = null;
  725. let logged = false;
  726. let attempt = 0;
  727. const debugLabel = getMessageDebugLabel(source, message);
  728. console.log(
  729. LOG_PREFIX,
  730. `[sendToContentScriptResilient] start ${debugLabel}, totalTimeout=${timeoutMs}ms, retryDelay=${retryDelayMs}ms`
  731. );
  732. while (Date.now() - start < timeoutMs) {
  733. throwIfStopped();
  734. attempt += 1;
  735. try {
  736. console.log(
  737. LOG_PREFIX,
  738. `[sendToContentScriptResilient] attempt ${attempt} -> ${debugLabel}, elapsed=${Date.now() - start}ms`
  739. );
  740. const result = await sendToContentScript(source, message);
  741. console.log(
  742. LOG_PREFIX,
  743. `[sendToContentScriptResilient] success ${debugLabel} on attempt ${attempt} after ${Date.now() - start}ms`
  744. );
  745. return result;
  746. } catch (err) {
  747. const retryable = isRetryableContentScriptTransportError(err);
  748. console.warn(
  749. LOG_PREFIX,
  750. `[sendToContentScriptResilient] attempt ${attempt} failed for ${debugLabel}, retryable=${retryable}, elapsed=${Date.now() - start}ms: ${err?.message || err}`
  751. );
  752. if (!retryable) {
  753. throw err;
  754. }
  755. lastError = err;
  756. if (logMessage && !logged) {
  757. await addLog(logMessage, 'warn');
  758. logged = true;
  759. }
  760. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  761. }
  762. }
  763. throw lastError || new Error(`等待 ${getSourceLabel(source)} 重新就绪超时。`);
  764. }
  765. async function sendToMailContentScriptResilient(mail, message, options = {}) {
  766. const { timeoutMs = 45000, maxRecoveryAttempts = 2 } = options;
  767. const start = Date.now();
  768. let lastError = null;
  769. let recoveries = 0;
  770. let logged = false;
  771. while (Date.now() - start < timeoutMs) {
  772. throwIfStopped();
  773. try {
  774. return await sendToContentScript(mail.source, message);
  775. } catch (err) {
  776. if (!isRetryableContentScriptTransportError(err)) {
  777. throw err;
  778. }
  779. lastError = err;
  780. if (!logged) {
  781. await addLog(`步骤 ${message.step}:${mail.label} 页面通信异常,正在尝试让邮箱页重新就绪...`, 'warn');
  782. logged = true;
  783. }
  784. if (recoveries >= maxRecoveryAttempts) {
  785. break;
  786. }
  787. recoveries += 1;
  788. await reuseOrCreateTab(mail.source, mail.url, {
  789. inject: mail.inject,
  790. injectSource: mail.injectSource,
  791. reloadIfSameUrl: true,
  792. });
  793. await new Promise((resolve) => setTimeout(resolve, 800));
  794. }
  795. }
  796. throw lastError || new Error(`${mail.label} 页面未能重新就绪。`);
  797. }
  798. // ============================================================
  799. // Logging
  800. // ============================================================
  801. async function addLog(message, level = 'info') {
  802. const state = await getState();
  803. const logs = state.logs || [];
  804. const entry = { message, level, timestamp: Date.now() };
  805. logs.push(entry);
  806. // Keep last 500 logs
  807. if (logs.length > 500) logs.splice(0, logs.length - 500);
  808. await setState({ logs });
  809. // Broadcast to side panel
  810. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => { });
  811. }
  812. function getStep8CallbackUrlFromNavigation(details, signupTabId) {
  813. if (!Number.isInteger(signupTabId) || !details) return '';
  814. if (details.tabId !== signupTabId) return '';
  815. if (details.frameId !== 0) return '';
  816. return isLocalhostOAuthCallbackUrl(details.url) ? details.url : '';
  817. }
  818. function getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId) {
  819. if (!Number.isInteger(signupTabId) || tabId !== signupTabId) return '';
  820. const candidates = [changeInfo?.url, tab?.url];
  821. for (const candidate of candidates) {
  822. if (isLocalhostOAuthCallbackUrl(candidate)) {
  823. return candidate;
  824. }
  825. }
  826. return '';
  827. }
  828. function getSourceLabel(source) {
  829. const labels = {
  830. 'sidepanel': '侧边栏',
  831. 'signup-page': '认证页',
  832. 'vps-panel': 'CPA 面板',
  833. 'qq-mail': 'QQ 邮箱',
  834. 'mail-163': '163 邮箱',
  835. 'inbucket-mail': 'Inbucket 邮箱',
  836. 'duck-mail': 'Duck 邮箱',
  837. };
  838. return labels[source] || source || '未知来源';
  839. }
  840. // ============================================================
  841. // Step Status Management
  842. // ============================================================
  843. async function setStepStatus(step, status) {
  844. const state = await getState();
  845. const statuses = { ...state.stepStatuses };
  846. statuses[step] = status;
  847. await setState({ stepStatuses: statuses, currentStep: step });
  848. // Broadcast to side panel
  849. chrome.runtime.sendMessage({
  850. type: 'STEP_STATUS_CHANGED',
  851. payload: { step, status },
  852. }).catch(() => { });
  853. }
  854. function isStopError(error) {
  855. const message = typeof error === 'string' ? error : error?.message;
  856. return message === STOP_ERROR_MESSAGE;
  857. }
  858. function isRetryableContentScriptTransportError(error) {
  859. const message = String(typeof error === 'string' ? error : error?.message || '');
  860. 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);
  861. }
  862. function getErrorMessage(error) {
  863. return String(typeof error === 'string' ? error : error?.message || '');
  864. }
  865. function isVerificationMailPollingError(error) {
  866. const message = getErrorMessage(error);
  867. return /未在 .*邮箱中找到新的匹配邮件|邮箱轮询结束,但未获取到验证码|无法获取新的(?:注册|登录)验证码|页面未能重新就绪|页面通信异常|did not respond in \d+s/i.test(message);
  868. }
  869. function isRestartCurrentAttemptError(error) {
  870. const message = String(typeof error === 'string' ? error : error?.message || '');
  871. return /当前邮箱已存在,需要重新开始新一轮/.test(message);
  872. }
  873. function isStep9OAuthTimeoutError(error) {
  874. const message = String(typeof error === 'string' ? error : error?.message || '');
  875. return /STEP9_OAUTH_TIMEOUT::|认证失败:\s*Timeout waiting for OAuth callback/i.test(message);
  876. }
  877. function isStepDoneStatus(status) {
  878. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  879. }
  880. function getFirstUnfinishedStep(statuses = {}) {
  881. for (let step = 1; step <= 9; step++) {
  882. if (!isStepDoneStatus(statuses[step] || 'pending')) {
  883. return step;
  884. }
  885. }
  886. return null;
  887. }
  888. function hasSavedProgress(statuses = {}) {
  889. return Object.values({ ...DEFAULT_STATE.stepStatuses, ...statuses }).some((status) => status !== 'pending');
  890. }
  891. function getDownstreamStateResets(step) {
  892. if (step <= 1) {
  893. return {
  894. oauthUrl: null,
  895. flowStartTime: null,
  896. password: null,
  897. lastEmailTimestamp: null,
  898. lastSignupCode: null,
  899. lastLoginCode: null,
  900. localhostUrl: null,
  901. };
  902. }
  903. if (step === 2) {
  904. return {
  905. password: null,
  906. lastEmailTimestamp: null,
  907. lastSignupCode: null,
  908. lastLoginCode: null,
  909. localhostUrl: null,
  910. };
  911. }
  912. if (step === 3 || step === 4) {
  913. return {
  914. lastEmailTimestamp: null,
  915. lastSignupCode: null,
  916. lastLoginCode: null,
  917. localhostUrl: null,
  918. };
  919. }
  920. if (step === 5 || step === 6 || step === 7) {
  921. return {
  922. lastLoginCode: null,
  923. localhostUrl: null,
  924. };
  925. }
  926. if (step === 8) {
  927. return {
  928. localhostUrl: null,
  929. };
  930. }
  931. return {};
  932. }
  933. async function invalidateDownstreamAfterStepRestart(step, options = {}) {
  934. const { logLabel = `步骤 ${step} 重新执行` } = options;
  935. const state = await getState();
  936. const statuses = { ...(state.stepStatuses || {}) };
  937. const changedSteps = [];
  938. for (let downstream = step + 1; downstream <= 9; downstream++) {
  939. if (statuses[downstream] !== 'pending') {
  940. statuses[downstream] = 'pending';
  941. changedSteps.push(downstream);
  942. }
  943. }
  944. if (changedSteps.length) {
  945. await setState({ stepStatuses: statuses });
  946. for (const downstream of changedSteps) {
  947. chrome.runtime.sendMessage({
  948. type: 'STEP_STATUS_CHANGED',
  949. payload: { step: downstream, status: 'pending' },
  950. }).catch(() => { });
  951. }
  952. await addLog(`${logLabel},已重置后续步骤状态:${changedSteps.join(', ')}`, 'warn');
  953. }
  954. const resets = getDownstreamStateResets(step);
  955. if (Object.keys(resets).length) {
  956. await setState(resets);
  957. broadcastDataUpdate(resets);
  958. }
  959. }
  960. function clearStopRequest() {
  961. stopRequested = false;
  962. }
  963. function getAutoRunStatusPayload(phase, payload = {}) {
  964. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  965. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  966. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  967. const rawScheduledAt = phase === 'scheduled'
  968. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  969. : null;
  970. const scheduledAt = rawScheduledAt === null ? null : Number(rawScheduledAt);
  971. const autoRunning = phase === 'scheduled' || phase === 'running' || phase === 'waiting_email' || phase === 'retrying';
  972. return {
  973. autoRunning,
  974. autoRunPhase: phase,
  975. autoRunCurrentRun: currentRun,
  976. autoRunTotalRuns: totalRuns,
  977. autoRunAttemptRun: attemptRun,
  978. scheduledAutoRunAt: Number.isFinite(scheduledAt) ? scheduledAt : null,
  979. };
  980. }
  981. async function broadcastAutoRunStatus(phase, payload = {}, extraState = {}) {
  982. const rawScheduledAt = phase === 'scheduled'
  983. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  984. : null;
  985. const statusPayload = {
  986. phase,
  987. currentRun: payload.currentRun ?? autoRunCurrentRun,
  988. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  989. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  990. scheduledAt: rawScheduledAt === null ? null : Number(rawScheduledAt),
  991. };
  992. await setState({
  993. ...extraState,
  994. ...getAutoRunStatusPayload(phase, statusPayload),
  995. });
  996. chrome.runtime.sendMessage({
  997. type: 'AUTO_RUN_STATUS',
  998. payload: statusPayload,
  999. }).catch(() => { });
  1000. }
  1001. function isAutoRunLockedState(state) {
  1002. return Boolean(state.autoRunning) && (state.autoRunPhase === 'running' || state.autoRunPhase === 'retrying');
  1003. }
  1004. function isAutoRunPausedState(state) {
  1005. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  1006. }
  1007. function isAutoRunScheduledState(state) {
  1008. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  1009. return Boolean(state.autoRunning)
  1010. && state.autoRunPhase === 'scheduled'
  1011. && Number.isFinite(scheduledAt)
  1012. && Boolean(normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan));
  1013. }
  1014. function formatAutoRunScheduleTime(timestamp) {
  1015. return new Date(timestamp).toLocaleString('zh-CN', {
  1016. hour12: false,
  1017. month: '2-digit',
  1018. day: '2-digit',
  1019. hour: '2-digit',
  1020. minute: '2-digit',
  1021. second: '2-digit',
  1022. });
  1023. }
  1024. async function ensureScheduledAutoRunAlarm(scheduledAt) {
  1025. if (!Number.isFinite(scheduledAt) || scheduledAt <= Date.now()) {
  1026. return false;
  1027. }
  1028. const existingAlarm = await chrome.alarms.get(AUTO_RUN_ALARM_NAME);
  1029. if (!existingAlarm || Math.abs((existingAlarm.scheduledTime || 0) - scheduledAt) > 1000) {
  1030. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  1031. await chrome.alarms.create(AUTO_RUN_ALARM_NAME, { when: scheduledAt });
  1032. }
  1033. return true;
  1034. }
  1035. async function clearScheduledAutoRunAlarm() {
  1036. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  1037. }
  1038. async function scheduleAutoRun(totalRuns, options = {}) {
  1039. const state = await getState();
  1040. if (isAutoRunLockedState(state) || isAutoRunPausedState(state) || autoRunActive) {
  1041. throw new Error('自动运行已在进行中,请先停止后再重新计划。');
  1042. }
  1043. if (isAutoRunScheduledState(state)) {
  1044. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  1045. }
  1046. const delayMinutes = normalizeAutoRunDelayMinutes(options.delayMinutes);
  1047. const plan = normalizeScheduledAutoRunPlan({
  1048. totalRuns,
  1049. autoRunSkipFailures: options.autoRunSkipFailures,
  1050. mode: options.mode,
  1051. });
  1052. const scheduledAt = Date.now() + delayMinutes * 60 * 1000;
  1053. autoRunCurrentRun = 0;
  1054. autoRunTotalRuns = plan.totalRuns;
  1055. autoRunAttemptRun = 0;
  1056. await ensureScheduledAutoRunAlarm(scheduledAt);
  1057. await broadcastAutoRunStatus(
  1058. 'scheduled',
  1059. {
  1060. currentRun: 0,
  1061. totalRuns: plan.totalRuns,
  1062. attemptRun: 0,
  1063. scheduledAt,
  1064. },
  1065. {
  1066. autoRunSkipFailures: plan.autoRunSkipFailures,
  1067. scheduledAutoRunPlan: plan,
  1068. }
  1069. );
  1070. await addLog(
  1071. `自动运行已计划:${delayMinutes} 分钟后启动(${formatAutoRunScheduleTime(scheduledAt)}),目标 ${plan.totalRuns} 轮。`,
  1072. 'info'
  1073. );
  1074. return { ok: true, scheduledAt };
  1075. }
  1076. let scheduledAutoRunLaunching = false;
  1077. async function launchScheduledAutoRun(trigger = 'alarm') {
  1078. if (scheduledAutoRunLaunching) {
  1079. return false;
  1080. }
  1081. scheduledAutoRunLaunching = true;
  1082. try {
  1083. const state = await getState();
  1084. if (!isAutoRunScheduledState(state)) {
  1085. return false;
  1086. }
  1087. if (autoRunActive) {
  1088. return false;
  1089. }
  1090. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1091. if (!plan) {
  1092. await clearScheduledAutoRunAlarm();
  1093. await broadcastAutoRunStatus('idle', {
  1094. currentRun: 0,
  1095. totalRuns: 1,
  1096. attemptRun: 0,
  1097. }, {
  1098. scheduledAutoRunPlan: null,
  1099. });
  1100. return false;
  1101. }
  1102. await clearScheduledAutoRunAlarm();
  1103. await broadcastAutoRunStatus(
  1104. 'running',
  1105. {
  1106. currentRun: 0,
  1107. totalRuns: plan.totalRuns,
  1108. attemptRun: 0,
  1109. },
  1110. {
  1111. autoRunSkipFailures: plan.autoRunSkipFailures,
  1112. scheduledAutoRunPlan: null,
  1113. }
  1114. );
  1115. clearStopRequest();
  1116. await addLog(
  1117. trigger === 'manual'
  1118. ? '已手动跳过倒计时,自动运行立即开始。'
  1119. : '倒计时结束,自动运行开始执行。',
  1120. 'info'
  1121. );
  1122. autoRunLoop(plan.totalRuns, {
  1123. autoRunSkipFailures: plan.autoRunSkipFailures,
  1124. mode: plan.mode,
  1125. });
  1126. return true;
  1127. } finally {
  1128. scheduledAutoRunLaunching = false;
  1129. }
  1130. }
  1131. async function cancelScheduledAutoRun(options = {}) {
  1132. const state = await getState();
  1133. if (!isAutoRunScheduledState(state)) {
  1134. return false;
  1135. }
  1136. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1137. await clearScheduledAutoRunAlarm();
  1138. autoRunCurrentRun = 0;
  1139. autoRunTotalRuns = plan?.totalRuns || 1;
  1140. autoRunAttemptRun = 0;
  1141. await broadcastAutoRunStatus(
  1142. 'idle',
  1143. {
  1144. currentRun: 0,
  1145. totalRuns: plan?.totalRuns || 1,
  1146. attemptRun: 0,
  1147. },
  1148. {
  1149. scheduledAutoRunPlan: null,
  1150. }
  1151. );
  1152. if (options.logMessage !== false) {
  1153. await addLog(options.logMessage || '已取消自动运行倒计时计划。', 'warn');
  1154. }
  1155. return true;
  1156. }
  1157. async function restoreScheduledAutoRunIfNeeded() {
  1158. const state = await getState();
  1159. if (state.autoRunPhase !== 'scheduled') {
  1160. return;
  1161. }
  1162. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1163. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  1164. if (!plan || !Number.isFinite(scheduledAt)) {
  1165. await clearScheduledAutoRunAlarm();
  1166. await broadcastAutoRunStatus('idle', {
  1167. currentRun: 0,
  1168. totalRuns: 1,
  1169. attemptRun: 0,
  1170. }, {
  1171. scheduledAutoRunPlan: null,
  1172. });
  1173. return;
  1174. }
  1175. if (scheduledAt <= Date.now()) {
  1176. await launchScheduledAutoRun('restore');
  1177. return;
  1178. }
  1179. await ensureScheduledAutoRunAlarm(scheduledAt);
  1180. }
  1181. async function ensureManualInteractionAllowed(actionLabel) {
  1182. const state = await getState();
  1183. if (isAutoRunLockedState(state)) {
  1184. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  1185. }
  1186. if (isAutoRunPausedState(state)) {
  1187. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  1188. }
  1189. if (isAutoRunScheduledState(state)) {
  1190. throw new Error(`自动流程已计划启动。请先取消计划,或立即开始后再${actionLabel}。`);
  1191. }
  1192. return state;
  1193. }
  1194. async function skipStep(step) {
  1195. const state = await ensureManualInteractionAllowed('跳过步骤');
  1196. if (!Number.isInteger(step) || step < 1 || step > 9) {
  1197. throw new Error(`无效步骤:${step}`);
  1198. }
  1199. const statuses = { ...(state.stepStatuses || {}) };
  1200. const currentStatus = statuses[step];
  1201. if (currentStatus === 'running') {
  1202. throw new Error(`步骤 ${step} 正在运行中,不能跳过。`);
  1203. }
  1204. if (isStepDoneStatus(currentStatus)) {
  1205. throw new Error(`步骤 ${step} 已完成,无需再跳过。`);
  1206. }
  1207. if (step > 1) {
  1208. const prevStatus = statuses[step - 1];
  1209. if (!isStepDoneStatus(prevStatus)) {
  1210. throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`);
  1211. }
  1212. }
  1213. await setStepStatus(step, 'skipped');
  1214. await addLog(`步骤 ${step} 已跳过`, 'warn');
  1215. if (step === 1) {
  1216. const latestState = await getState();
  1217. const step2Status = latestState.stepStatuses?.[2];
  1218. if (!isStepDoneStatus(step2Status) && step2Status !== 'running') {
  1219. await setStepStatus(2, 'skipped');
  1220. await addLog('步骤 1 已跳过,步骤 2 也已同时跳过。', 'warn');
  1221. }
  1222. }
  1223. return { ok: true, step, status: 'skipped' };
  1224. }
  1225. function throwIfStopped() {
  1226. if (stopRequested) {
  1227. throw new Error(STOP_ERROR_MESSAGE);
  1228. }
  1229. }
  1230. async function sleepWithStop(ms) {
  1231. const start = Date.now();
  1232. while (Date.now() - start < ms) {
  1233. throwIfStopped();
  1234. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  1235. }
  1236. }
  1237. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  1238. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  1239. await sleepWithStop(duration);
  1240. }
  1241. async function clickWithDebugger(tabId, rect) {
  1242. if (!tabId) {
  1243. throw new Error('未找到用于调试点击的认证页面标签页。');
  1244. }
  1245. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  1246. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  1247. }
  1248. const target = { tabId };
  1249. try {
  1250. await chrome.debugger.attach(target, '1.3');
  1251. } catch (err) {
  1252. throw new Error(
  1253. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  1254. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  1255. );
  1256. }
  1257. try {
  1258. const x = Math.round(rect.centerX);
  1259. const y = Math.round(rect.centerY);
  1260. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  1261. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1262. type: 'mouseMoved',
  1263. x,
  1264. y,
  1265. button: 'none',
  1266. buttons: 0,
  1267. clickCount: 0,
  1268. });
  1269. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1270. type: 'mousePressed',
  1271. x,
  1272. y,
  1273. button: 'left',
  1274. buttons: 1,
  1275. clickCount: 1,
  1276. });
  1277. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1278. type: 'mouseReleased',
  1279. x,
  1280. y,
  1281. button: 'left',
  1282. buttons: 0,
  1283. clickCount: 1,
  1284. });
  1285. } finally {
  1286. await chrome.debugger.detach(target).catch(() => { });
  1287. }
  1288. }
  1289. async function broadcastStopToContentScripts() {
  1290. const registry = await getTabRegistry();
  1291. for (const entry of Object.values(registry)) {
  1292. if (!entry?.tabId) continue;
  1293. try {
  1294. await chrome.tabs.sendMessage(entry.tabId, {
  1295. type: 'STOP_FLOW',
  1296. source: 'background',
  1297. payload: {},
  1298. });
  1299. } catch { }
  1300. }
  1301. }
  1302. let stopRequested = false;
  1303. // ============================================================
  1304. // Message Handler (central router)
  1305. // ============================================================
  1306. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  1307. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  1308. handleMessage(message, sender).then(response => {
  1309. sendResponse(response);
  1310. }).catch(err => {
  1311. console.error(LOG_PREFIX, 'Handler error:', err);
  1312. sendResponse({ error: err.message });
  1313. });
  1314. return true; // async response
  1315. });
  1316. async function handleMessage(message, sender) {
  1317. switch (message.type) {
  1318. case 'CONTENT_SCRIPT_READY': {
  1319. const tabId = sender.tab?.id;
  1320. if (tabId && message.source) {
  1321. await registerTab(message.source, tabId);
  1322. flushCommand(message.source, tabId);
  1323. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  1324. }
  1325. return { ok: true };
  1326. }
  1327. case 'LOG': {
  1328. const { message: msg, level } = message.payload;
  1329. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  1330. return { ok: true };
  1331. }
  1332. case 'STEP_COMPLETE': {
  1333. if (stopRequested) {
  1334. await setStepStatus(message.step, 'stopped');
  1335. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  1336. return { ok: true };
  1337. }
  1338. await setStepStatus(message.step, 'completed');
  1339. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  1340. await handleStepData(message.step, message.payload);
  1341. notifyStepComplete(message.step, message.payload);
  1342. return { ok: true };
  1343. }
  1344. case 'STEP_ERROR': {
  1345. if (isStopError(message.error)) {
  1346. await setStepStatus(message.step, 'stopped');
  1347. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  1348. notifyStepError(message.step, message.error);
  1349. } else {
  1350. await setStepStatus(message.step, 'failed');
  1351. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  1352. notifyStepError(message.step, message.error);
  1353. }
  1354. return { ok: true };
  1355. }
  1356. case 'GET_STATE': {
  1357. return await getState();
  1358. }
  1359. case 'RESET': {
  1360. clearStopRequest();
  1361. await clearScheduledAutoRunAlarm();
  1362. await resetState();
  1363. await addLog('流程已重置', 'info');
  1364. return { ok: true };
  1365. }
  1366. case 'EXECUTE_STEP': {
  1367. clearStopRequest();
  1368. if (message.source === 'sidepanel') {
  1369. await ensureManualInteractionAllowed('手动执行步骤');
  1370. }
  1371. const step = message.payload.step;
  1372. if (message.source === 'sidepanel') {
  1373. await invalidateDownstreamAfterStepRestart(step, { logLabel: `步骤 ${step} 重新执行` });
  1374. }
  1375. // Save email if provided (from side panel step 3)
  1376. if (message.payload.email) {
  1377. await setEmailState(message.payload.email);
  1378. }
  1379. await executeStep(step);
  1380. return { ok: true };
  1381. }
  1382. case 'AUTO_RUN': {
  1383. clearStopRequest();
  1384. const state = await getState();
  1385. if (isAutoRunScheduledState(state)) {
  1386. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  1387. }
  1388. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  1389. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  1390. const mode = message.payload?.mode === 'continue' ? 'continue' : 'restart';
  1391. await setState({ autoRunSkipFailures });
  1392. autoRunLoop(totalRuns, { autoRunSkipFailures, mode }); // fire-and-forget
  1393. return { ok: true };
  1394. }
  1395. case 'SCHEDULE_AUTO_RUN': {
  1396. clearStopRequest();
  1397. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  1398. return await scheduleAutoRun(totalRuns, {
  1399. delayMinutes: message.payload?.delayMinutes,
  1400. autoRunSkipFailures: Boolean(message.payload?.autoRunSkipFailures),
  1401. mode: message.payload?.mode,
  1402. });
  1403. }
  1404. case 'START_SCHEDULED_AUTO_RUN_NOW': {
  1405. clearStopRequest();
  1406. const started = await launchScheduledAutoRun('manual');
  1407. if (!started) {
  1408. throw new Error('当前没有可立即开始的倒计时计划。');
  1409. }
  1410. return { ok: true };
  1411. }
  1412. case 'CANCEL_SCHEDULED_AUTO_RUN': {
  1413. const cancelled = await cancelScheduledAutoRun();
  1414. if (!cancelled) {
  1415. throw new Error('当前没有可取消的倒计时计划。');
  1416. }
  1417. return { ok: true };
  1418. }
  1419. case 'RESUME_AUTO_RUN': {
  1420. clearStopRequest();
  1421. if (message.payload.email) {
  1422. await setEmailState(message.payload.email);
  1423. }
  1424. resumeAutoRun(); // fire-and-forget
  1425. return { ok: true };
  1426. }
  1427. case 'TAKEOVER_AUTO_RUN': {
  1428. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  1429. await addLog('自动流程已切换为手动控制。', 'warn');
  1430. return { ok: true };
  1431. }
  1432. case 'SKIP_STEP': {
  1433. const step = Number(message.payload?.step);
  1434. return await skipStep(step);
  1435. }
  1436. case 'SAVE_SETTING': {
  1437. const updates = {};
  1438. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  1439. if (message.payload.vpsPassword !== undefined) updates.vpsPassword = message.payload.vpsPassword;
  1440. if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
  1441. if (message.payload.autoRunSkipFailures !== undefined) updates.autoRunSkipFailures = Boolean(message.payload.autoRunSkipFailures);
  1442. if (message.payload.autoRunDelayEnabled !== undefined) updates.autoRunDelayEnabled = Boolean(message.payload.autoRunDelayEnabled);
  1443. if (message.payload.autoRunDelayMinutes !== undefined) updates.autoRunDelayMinutes = normalizeAutoRunDelayMinutes(message.payload.autoRunDelayMinutes);
  1444. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  1445. if (message.payload.inbucketHost !== undefined) updates.inbucketHost = message.payload.inbucketHost;
  1446. if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
  1447. await setPersistentSettings(updates);
  1448. await setState(updates);
  1449. return { ok: true };
  1450. }
  1451. // Side panel data updates
  1452. case 'SAVE_EMAIL': {
  1453. const state = await getState();
  1454. if (isAutoRunLockedState(state)) {
  1455. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  1456. }
  1457. await setEmailState(message.payload.email);
  1458. await resumeAutoRun();
  1459. return { ok: true, email: message.payload.email };
  1460. }
  1461. case 'FETCH_DUCK_EMAIL': {
  1462. clearStopRequest();
  1463. const state = await getState();
  1464. if (isAutoRunLockedState(state)) {
  1465. throw new Error('自动流程运行中,当前不能手动获取 Duck 邮箱。');
  1466. }
  1467. const email = await fetchDuckEmail(message.payload || {});
  1468. await resumeAutoRun();
  1469. return { ok: true, email };
  1470. }
  1471. case 'STOP_FLOW': {
  1472. await requestStop();
  1473. return { ok: true };
  1474. }
  1475. default:
  1476. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  1477. return { error: `Unknown message type: ${message.type}` };
  1478. }
  1479. }
  1480. // ============================================================
  1481. // Step Data Handlers
  1482. // ============================================================
  1483. async function handleStepData(step, payload) {
  1484. switch (step) {
  1485. case 1:
  1486. if (payload.oauthUrl) {
  1487. await setState({ oauthUrl: payload.oauthUrl });
  1488. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  1489. }
  1490. break;
  1491. case 3:
  1492. if (payload.email) await setEmailState(payload.email);
  1493. break;
  1494. case 4:
  1495. if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
  1496. break;
  1497. case 8:
  1498. if (payload.localhostUrl) {
  1499. if (!isLocalhostOAuthCallbackUrl(payload.localhostUrl)) {
  1500. throw new Error('步骤 8 返回了无效的 localhost OAuth 回调地址。');
  1501. }
  1502. await setState({ localhostUrl: payload.localhostUrl });
  1503. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  1504. }
  1505. break;
  1506. case 9: {
  1507. if (payload.localhostUrl) {
  1508. await closeLocalhostCallbackTabs(payload.localhostUrl);
  1509. }
  1510. break;
  1511. }
  1512. }
  1513. }
  1514. // ============================================================
  1515. // Step Completion Waiting
  1516. // ============================================================
  1517. // Map of step -> { resolve, reject } for waiting on step completion
  1518. const stepWaiters = new Map();
  1519. let resumeWaiter = null;
  1520. const AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS = 120000;
  1521. const AUTO_RUN_BACKGROUND_COMPLETED_STEPS = new Set([4, 7, 8]);
  1522. function waitForStepComplete(step, timeoutMs = 120000) {
  1523. return new Promise((resolve, reject) => {
  1524. throwIfStopped();
  1525. if (stepWaiters.has(step)) {
  1526. console.warn(LOG_PREFIX, `[waitForStepComplete] replacing existing waiter for step ${step}`);
  1527. }
  1528. console.log(LOG_PREFIX, `[waitForStepComplete] register step ${step}, timeout=${timeoutMs}ms`);
  1529. const timer = setTimeout(() => {
  1530. stepWaiters.delete(step);
  1531. console.warn(LOG_PREFIX, `[waitForStepComplete] timeout for step ${step} after ${timeoutMs}ms`);
  1532. reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
  1533. }, timeoutMs);
  1534. stepWaiters.set(step, {
  1535. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  1536. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  1537. });
  1538. });
  1539. }
  1540. function notifyStepComplete(step, payload) {
  1541. const waiter = stepWaiters.get(step);
  1542. console.log(LOG_PREFIX, `[notifyStepComplete] step ${step}, hasWaiter=${Boolean(waiter)}`);
  1543. if (waiter) waiter.resolve(payload);
  1544. }
  1545. function notifyStepError(step, error) {
  1546. const waiter = stepWaiters.get(step);
  1547. console.warn(LOG_PREFIX, `[notifyStepError] step ${step}, hasWaiter=${Boolean(waiter)}, error=${error}`);
  1548. if (waiter) waiter.reject(new Error(error));
  1549. }
  1550. async function completeStepFromBackground(step, payload = {}) {
  1551. if (stopRequested) {
  1552. await setStepStatus(step, 'stopped');
  1553. notifyStepError(step, STOP_ERROR_MESSAGE);
  1554. return;
  1555. }
  1556. await setStepStatus(step, 'completed');
  1557. await addLog(`步骤 ${step} 已完成`, 'ok');
  1558. await handleStepData(step, payload);
  1559. notifyStepComplete(step, payload);
  1560. }
  1561. async function markRunningStepsStopped() {
  1562. const state = await getState();
  1563. const runningSteps = Object.entries(state.stepStatuses || {})
  1564. .filter(([, status]) => status === 'running')
  1565. .map(([step]) => Number(step));
  1566. for (const step of runningSteps) {
  1567. await setStepStatus(step, 'stopped');
  1568. }
  1569. }
  1570. async function requestStop(options = {}) {
  1571. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  1572. const state = await getState();
  1573. if (isAutoRunScheduledState(state) && !autoRunActive) {
  1574. await cancelScheduledAutoRun({
  1575. logMessage: options.logMessage === false
  1576. ? false
  1577. : (options.logMessage || '已取消自动运行倒计时计划。'),
  1578. });
  1579. return;
  1580. }
  1581. if (stopRequested) return;
  1582. stopRequested = true;
  1583. cancelPendingCommands();
  1584. cleanupStep8NavigationListeners();
  1585. rejectPendingStep8(new Error(STOP_ERROR_MESSAGE));
  1586. await addLog(logMessage, 'warn');
  1587. await broadcastStopToContentScripts();
  1588. for (const waiter of stepWaiters.values()) {
  1589. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  1590. }
  1591. stepWaiters.clear();
  1592. if (resumeWaiter) {
  1593. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  1594. resumeWaiter = null;
  1595. }
  1596. await markRunningStepsStopped();
  1597. autoRunActive = false;
  1598. await broadcastAutoRunStatus('stopped', {
  1599. currentRun: autoRunCurrentRun,
  1600. totalRuns: autoRunTotalRuns,
  1601. attemptRun: autoRunAttemptRun,
  1602. });
  1603. }
  1604. // ============================================================
  1605. // Step Execution
  1606. // ============================================================
  1607. async function executeStep(step) {
  1608. console.log(LOG_PREFIX, `Executing step ${step}`);
  1609. throwIfStopped();
  1610. await setStepStatus(step, 'running');
  1611. await addLog(`步骤 ${step} 开始执行`);
  1612. await humanStepDelay();
  1613. const state = await getState();
  1614. // Set flow start time on first step
  1615. if (step === 1 && !state.flowStartTime) {
  1616. await setState({ flowStartTime: Date.now() });
  1617. }
  1618. try {
  1619. switch (step) {
  1620. case 1: await executeStep1(state); break;
  1621. case 2: await executeStep2(state); break;
  1622. case 3: await executeStep3(state); break;
  1623. case 4: await executeStep4(state); break;
  1624. case 5: await executeStep5(state); break;
  1625. case 6: await executeStep6(state); break;
  1626. case 7: await executeStep7(state); break;
  1627. case 8: await executeStep8(state); break;
  1628. case 9: await executeStep9(state); break;
  1629. default:
  1630. throw new Error(`未知步骤:${step}`);
  1631. }
  1632. } catch (err) {
  1633. if (isStopError(err)) {
  1634. await setStepStatus(step, 'stopped');
  1635. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  1636. throw err;
  1637. }
  1638. await setStepStatus(step, 'failed');
  1639. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  1640. throw err;
  1641. }
  1642. }
  1643. /**
  1644. * Execute a step and wait for it to complete before returning.
  1645. * @param {number} step
  1646. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  1647. */
  1648. async function executeStepAndWait(step, delayAfter = 2000) {
  1649. throwIfStopped();
  1650. if (AUTO_RUN_BACKGROUND_COMPLETED_STEPS.has(step)) {
  1651. await addLog(`自动运行:步骤 ${step} 由后台流程负责收尾,执行函数返回后将直接进入下一步。`, 'info');
  1652. await executeStep(step);
  1653. const latestState = await getState();
  1654. await addLog(`自动运行:步骤 ${step} 已执行返回,当前状态为 ${latestState.stepStatuses?.[step] || 'pending'},准备继续后续步骤。`, 'info');
  1655. } else {
  1656. await addLog(`自动运行:步骤 ${step} 已发起,正在等待完成信号(超时 ${AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS / 1000} 秒)。`, 'info');
  1657. const completionResultPromise = waitForStepComplete(step, AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS).then(
  1658. payload => ({ ok: true, payload }),
  1659. error => ({ ok: false, error }),
  1660. );
  1661. try {
  1662. await executeStep(step);
  1663. } catch (err) {
  1664. notifyStepError(step, getErrorMessage(err));
  1665. await completionResultPromise;
  1666. throw err;
  1667. }
  1668. const completionResult = await completionResultPromise;
  1669. if (!completionResult.ok) {
  1670. throw completionResult.error;
  1671. }
  1672. await addLog(`自动运行:步骤 ${step} 已收到完成信号,准备继续后续步骤。`, 'info');
  1673. }
  1674. // Extra delay for page transitions / DOM updates
  1675. if (delayAfter > 0) {
  1676. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  1677. }
  1678. }
  1679. async function fetchDuckEmail(options = {}) {
  1680. throwIfStopped();
  1681. const { generateNew = true } = options;
  1682. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  1683. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  1684. const result = await sendToContentScript('duck-mail', {
  1685. type: 'FETCH_DUCK_EMAIL',
  1686. source: 'background',
  1687. payload: { generateNew },
  1688. });
  1689. if (result?.error) {
  1690. throw new Error(result.error);
  1691. }
  1692. if (!result?.email) {
  1693. throw new Error('未返回 Duck 邮箱地址。');
  1694. }
  1695. await setEmailState(result.email);
  1696. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  1697. return result.email;
  1698. }
  1699. // ============================================================
  1700. // Auto Run Flow
  1701. // ============================================================
  1702. let autoRunActive = false;
  1703. let autoRunCurrentRun = 0;
  1704. let autoRunTotalRuns = 1;
  1705. let autoRunAttemptRun = 0;
  1706. const DUCK_EMAIL_MAX_ATTEMPTS = 5;
  1707. const VERIFICATION_POLL_MAX_ROUNDS = 5;
  1708. const AUTO_STEP_DELAYS = {
  1709. 1: 2000,
  1710. 2: 2000,
  1711. 3: 3000,
  1712. 4: 2000,
  1713. 5: 3000,
  1714. 6: 3000,
  1715. 7: 2000,
  1716. 8: 2000,
  1717. 9: 1000,
  1718. };
  1719. async function resumeAutoRunIfWaitingForEmail(options = {}) {
  1720. const { silent = false } = options;
  1721. const state = await getState();
  1722. if (!state.email || !isAutoRunPausedState(state)) {
  1723. return false;
  1724. }
  1725. if (resumeWaiter) {
  1726. if (!silent) {
  1727. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  1728. }
  1729. resumeWaiter.resolve();
  1730. resumeWaiter = null;
  1731. return true;
  1732. }
  1733. return false;
  1734. }
  1735. async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
  1736. const currentState = await getState();
  1737. if (currentState.email) {
  1738. return currentState.email;
  1739. }
  1740. let lastDuckError = null;
  1741. for (let duckAttempt = 1; duckAttempt <= DUCK_EMAIL_MAX_ATTEMPTS; duckAttempt++) {
  1742. try {
  1743. if (duckAttempt > 1) {
  1744. await addLog(`Duck 邮箱:正在进行第 ${duckAttempt}/${DUCK_EMAIL_MAX_ATTEMPTS} 次自动获取重试...`, 'warn');
  1745. }
  1746. const duckEmail = await fetchDuckEmail({ generateNew: true });
  1747. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:Duck 邮箱已就绪:${duckEmail}(第 ${attemptRuns} 次尝试,Duck 第 ${duckAttempt}/${DUCK_EMAIL_MAX_ATTEMPTS} 次获取)===`, 'ok');
  1748. return duckEmail;
  1749. } catch (err) {
  1750. lastDuckError = err;
  1751. await addLog(`Duck 邮箱自动获取失败(${duckAttempt}/${DUCK_EMAIL_MAX_ATTEMPTS}):${err.message}`, 'warn');
  1752. }
  1753. }
  1754. await addLog(`Duck 邮箱自动获取已连续失败 ${DUCK_EMAIL_MAX_ATTEMPTS} 次:${lastDuckError?.message || '未知错误'}`, 'error');
  1755. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先获取 Duck 邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  1756. await broadcastAutoRunStatus('waiting_email', {
  1757. currentRun: targetRun,
  1758. totalRuns,
  1759. attemptRun: attemptRuns,
  1760. });
  1761. await waitForResume();
  1762. const resumedState = await getState();
  1763. if (!resumedState.email) {
  1764. throw new Error('无法继续:当前没有邮箱地址。');
  1765. }
  1766. return resumedState.email;
  1767. }
  1768. async function runAutoSequenceFromStep(startStep, context = {}) {
  1769. const { targetRun, totalRuns, attemptRuns, continued = false } = context;
  1770. const maxStep9RestartAttempts = 5;
  1771. let step9RestartAttempts = 0;
  1772. if (continued) {
  1773. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续当前进度,从步骤 ${startStep} 开始(第 ${attemptRuns} 次尝试)===`, 'info');
  1774. } else {
  1775. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  1776. }
  1777. if (startStep <= 2) {
  1778. for (const step of [1, 2]) {
  1779. if (step < startStep) continue;
  1780. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1781. }
  1782. }
  1783. if (startStep <= 3) {
  1784. await ensureAutoEmailReady(targetRun, totalRuns, attemptRuns);
  1785. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  1786. await broadcastAutoRunStatus('running', {
  1787. currentRun: targetRun,
  1788. totalRuns,
  1789. attemptRun: attemptRuns,
  1790. });
  1791. await executeStepAndWait(3, AUTO_STEP_DELAYS[3]);
  1792. } else {
  1793. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续执行剩余流程(第 ${attemptRuns} 次尝试)===`, 'info');
  1794. }
  1795. const signupTabId = await getTabId('signup-page');
  1796. if (signupTabId) {
  1797. await chrome.tabs.update(signupTabId, { active: true });
  1798. }
  1799. let step = Math.max(startStep, 4);
  1800. while (step <= 9) {
  1801. try {
  1802. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1803. step += 1;
  1804. } catch (err) {
  1805. if (step === 9 && isStep9OAuthTimeoutError(err) && step9RestartAttempts < maxStep9RestartAttempts) {
  1806. step9RestartAttempts += 1;
  1807. await addLog(
  1808. `步骤 9:检测到 OAuth callback 超时,正在回到步骤 6 重新开始授权流程(${step9RestartAttempts}/${maxStep9RestartAttempts})...`,
  1809. 'warn'
  1810. );
  1811. await invalidateDownstreamAfterStepRestart(6, {
  1812. logLabel: `步骤 9 超时后准备回到步骤 6 重试(${step9RestartAttempts}/${maxStep9RestartAttempts})`,
  1813. });
  1814. step = 6;
  1815. continue;
  1816. }
  1817. throw err;
  1818. }
  1819. }
  1820. }
  1821. // Outer loop: keep retrying until the target number of successful runs is reached.
  1822. async function autoRunLoop(totalRuns, options = {}) {
  1823. if (autoRunActive) {
  1824. await addLog('自动运行已在进行中', 'warn');
  1825. return;
  1826. }
  1827. clearStopRequest();
  1828. autoRunActive = true;
  1829. autoRunTotalRuns = totalRuns;
  1830. autoRunCurrentRun = 0;
  1831. autoRunAttemptRun = 0;
  1832. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  1833. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  1834. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) ? options.resumeCurrentRun : 0;
  1835. const resumeSuccessfulRuns = Number.isInteger(options.resumeSuccessfulRuns) ? options.resumeSuccessfulRuns : 0;
  1836. const resumeAttemptRunsProcessed = Number.isInteger(options.resumeAttemptRunsProcessed) ? options.resumeAttemptRunsProcessed : 0;
  1837. let maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  1838. const forcedRetryCap = Math.max(totalRuns * 10, totalRuns + 20);
  1839. let successfulRuns = Math.max(0, resumeSuccessfulRuns);
  1840. let attemptRuns = Math.max(0, resumeAttemptRunsProcessed);
  1841. let forceFreshTabsNextRun = false;
  1842. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  1843. await setState({
  1844. autoRunSkipFailures,
  1845. ...getAutoRunStatusPayload('running', {
  1846. currentRun: resumeCurrentRun,
  1847. totalRuns,
  1848. attemptRun: resumeAttemptRunsProcessed,
  1849. }),
  1850. });
  1851. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  1852. attemptRuns += 1;
  1853. const targetRun = successfulRuns + 1;
  1854. autoRunCurrentRun = targetRun;
  1855. autoRunAttemptRun = attemptRuns;
  1856. let startStep = 1;
  1857. let useExistingProgress = false;
  1858. if (continueCurrentOnFirstAttempt) {
  1859. const currentState = await getState();
  1860. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  1861. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  1862. startStep = resumeStep;
  1863. useExistingProgress = true;
  1864. } else if (hasSavedProgress(currentState.stepStatuses)) {
  1865. await addLog('当前流程已全部处理,将按“重新开始”新开一轮自动运行。', 'info');
  1866. }
  1867. continueCurrentOnFirstAttempt = false;
  1868. }
  1869. if (!useExistingProgress) {
  1870. // Reset everything at the start of each fresh attempt (keep user settings).
  1871. const prevState = await getState();
  1872. const keepSettings = {
  1873. vpsUrl: prevState.vpsUrl,
  1874. vpsPassword: prevState.vpsPassword,
  1875. customPassword: prevState.customPassword,
  1876. autoRunSkipFailures: prevState.autoRunSkipFailures,
  1877. mailProvider: prevState.mailProvider,
  1878. inbucketHost: prevState.inbucketHost,
  1879. inbucketMailbox: prevState.inbucketMailbox,
  1880. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  1881. ...(forceFreshTabsNextRun ? { tabRegistry: {} } : {}),
  1882. };
  1883. await resetState();
  1884. await setState(keepSettings);
  1885. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => { });
  1886. await sleepWithStop(500);
  1887. } else {
  1888. await setState({
  1889. autoRunSkipFailures,
  1890. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  1891. });
  1892. }
  1893. if (forceFreshTabsNextRun) {
  1894. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  1895. forceFreshTabsNextRun = false;
  1896. }
  1897. try {
  1898. throwIfStopped();
  1899. await broadcastAutoRunStatus('running', {
  1900. currentRun: targetRun,
  1901. totalRuns,
  1902. attemptRun: attemptRuns,
  1903. });
  1904. await runAutoSequenceFromStep(startStep, {
  1905. targetRun,
  1906. totalRuns,
  1907. attemptRuns,
  1908. continued: useExistingProgress,
  1909. });
  1910. successfulRuns += 1;
  1911. autoRunCurrentRun = successfulRuns;
  1912. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  1913. continue;
  1914. } catch (err) {
  1915. if (isStopError(err)) {
  1916. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  1917. await broadcastAutoRunStatus('stopped', {
  1918. currentRun: targetRun,
  1919. totalRuns,
  1920. attemptRun: attemptRuns,
  1921. });
  1922. break;
  1923. }
  1924. if (isRestartCurrentAttemptError(err)) {
  1925. await addLog(`目标 ${targetRun}/${totalRuns} 轮检测到当前邮箱已存在,当前线程已放弃,将重新开始新一轮。`, 'warn');
  1926. cancelPendingCommands('当前线程因邮箱已存在而放弃。');
  1927. await broadcastStopToContentScripts();
  1928. await broadcastAutoRunStatus('retrying', {
  1929. currentRun: targetRun,
  1930. totalRuns,
  1931. attemptRun: attemptRuns,
  1932. });
  1933. forceFreshTabsNextRun = true;
  1934. maxAttempts = Math.max(maxAttempts, Math.min(forcedRetryCap, attemptRuns + 1));
  1935. continue;
  1936. }
  1937. if (!autoRunSkipFailures) {
  1938. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  1939. await broadcastAutoRunStatus('stopped', {
  1940. currentRun: targetRun,
  1941. totalRuns,
  1942. attemptRun: attemptRuns,
  1943. });
  1944. break;
  1945. }
  1946. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  1947. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  1948. cancelPendingCommands('当前尝试已放弃。');
  1949. await broadcastStopToContentScripts();
  1950. await broadcastAutoRunStatus('retrying', {
  1951. currentRun: targetRun,
  1952. totalRuns,
  1953. attemptRun: attemptRuns,
  1954. });
  1955. forceFreshTabsNextRun = true;
  1956. }
  1957. }
  1958. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  1959. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  1960. await broadcastAutoRunStatus('stopped', {
  1961. currentRun: successfulRuns,
  1962. totalRuns: autoRunTotalRuns,
  1963. attemptRun: attemptRuns,
  1964. });
  1965. } else if (stopRequested) {
  1966. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1967. await broadcastAutoRunStatus('stopped', {
  1968. currentRun: successfulRuns,
  1969. totalRuns: autoRunTotalRuns,
  1970. attemptRun: attemptRuns,
  1971. });
  1972. } else if (successfulRuns >= autoRunTotalRuns) {
  1973. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  1974. await broadcastAutoRunStatus('complete', {
  1975. currentRun: successfulRuns,
  1976. totalRuns: autoRunTotalRuns,
  1977. attemptRun: attemptRuns,
  1978. });
  1979. } else {
  1980. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1981. await broadcastAutoRunStatus('stopped', {
  1982. currentRun: successfulRuns,
  1983. totalRuns: autoRunTotalRuns,
  1984. attemptRun: attemptRuns,
  1985. });
  1986. }
  1987. autoRunActive = false;
  1988. autoRunAttemptRun = attemptRuns;
  1989. await setState(getAutoRunStatusPayload(stopRequested ? 'stopped' : (successfulRuns >= autoRunTotalRuns ? 'complete' : 'stopped'), {
  1990. currentRun: successfulRuns,
  1991. totalRuns: autoRunTotalRuns,
  1992. attemptRun: attemptRuns,
  1993. }));
  1994. clearStopRequest();
  1995. }
  1996. async function waitForResume() {
  1997. throwIfStopped();
  1998. const state = await getState();
  1999. if (state.email) {
  2000. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  2001. return;
  2002. }
  2003. return new Promise((resolve, reject) => {
  2004. resumeWaiter = { resolve, reject };
  2005. });
  2006. }
  2007. async function resumeAutoRun() {
  2008. throwIfStopped();
  2009. const state = await getState();
  2010. if (!state.email) {
  2011. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  2012. return false;
  2013. }
  2014. const resumedInMemory = await resumeAutoRunIfWaitingForEmail({ silent: true });
  2015. if (resumedInMemory) {
  2016. return true;
  2017. }
  2018. if (!isAutoRunPausedState(state)) {
  2019. return false;
  2020. }
  2021. if (autoRunActive) {
  2022. return false;
  2023. }
  2024. const totalRuns = state.autoRunTotalRuns || 1;
  2025. const currentRun = state.autoRunCurrentRun || 1;
  2026. const attemptRun = state.autoRunAttemptRun || 1;
  2027. const successfulRuns = Math.max(0, currentRun - 1);
  2028. await addLog('检测到自动流程暂停上下文已丢失,正在从当前进度恢复自动运行...', 'warn');
  2029. autoRunLoop(totalRuns, {
  2030. autoRunSkipFailures: Boolean(state.autoRunSkipFailures),
  2031. mode: 'continue',
  2032. resumeCurrentRun: currentRun,
  2033. resumeSuccessfulRuns: successfulRuns,
  2034. resumeAttemptRunsProcessed: Math.max(0, attemptRun - 1),
  2035. });
  2036. return true;
  2037. }
  2038. // ============================================================
  2039. // Step 1: Get OAuth Link (via vps-panel.js)
  2040. // ============================================================
  2041. async function executeStep1(state) {
  2042. if (!state.vpsUrl) {
  2043. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  2044. }
  2045. await addLog('步骤 1:正在打开 CPA 面板...');
  2046. const injectFiles = ['content/utils.js', 'content/vps-panel.js'];
  2047. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  2048. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  2049. const tabId = tab.id;
  2050. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  2051. await addLog('步骤 1:CPA 面板已打开,正在等待页面进入目标地址...');
  2052. const matchedTab = await waitForTabUrlFamily('vps-panel', tabId, state.vpsUrl, {
  2053. timeoutMs: 15000,
  2054. retryDelayMs: 400,
  2055. });
  2056. if (!matchedTab) {
  2057. await addLog('步骤 1:CPA 页面尚未完全进入目标地址,继续尝试连接内容脚本...', 'warn');
  2058. }
  2059. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  2060. inject: injectFiles,
  2061. timeoutMs: 45000,
  2062. retryDelayMs: 900,
  2063. logMessage: '步骤 1:CPA 面板仍在加载,正在重试连接内容脚本...',
  2064. });
  2065. const result = await sendToContentScriptResilient('vps-panel', {
  2066. type: 'EXECUTE_STEP',
  2067. step: 1,
  2068. source: 'background',
  2069. payload: { vpsPassword: state.vpsPassword },
  2070. }, {
  2071. timeoutMs: 30000,
  2072. retryDelayMs: 700,
  2073. logMessage: '步骤 1:CPA 面板通信未就绪,正在等待页面恢复...',
  2074. });
  2075. if (result?.error) {
  2076. throw new Error(result.error);
  2077. }
  2078. }
  2079. // ============================================================
  2080. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  2081. // ============================================================
  2082. async function executeStep2(state) {
  2083. if (!state.oauthUrl) {
  2084. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  2085. }
  2086. await addLog('步骤 2:正在打开认证链接...');
  2087. await reuseOrCreateTab('signup-page', state.oauthUrl);
  2088. await sendToContentScript('signup-page', {
  2089. type: 'EXECUTE_STEP',
  2090. step: 2,
  2091. source: 'background',
  2092. payload: {},
  2093. });
  2094. }
  2095. // ============================================================
  2096. // Step 3: Fill Email & Password (via signup-page.js)
  2097. // ============================================================
  2098. async function executeStep3(state) {
  2099. if (!state.email) {
  2100. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  2101. }
  2102. const password = state.customPassword || generatePassword();
  2103. await setPasswordState(password);
  2104. // Save account record
  2105. const accounts = state.accounts || [];
  2106. accounts.push({ email: state.email, password, createdAt: new Date().toISOString() });
  2107. await setState({ accounts });
  2108. await addLog(
  2109. `步骤 3:正在填写邮箱 ${state.email},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  2110. );
  2111. await sendToContentScript('signup-page', {
  2112. type: 'EXECUTE_STEP',
  2113. step: 3,
  2114. source: 'background',
  2115. payload: { email: state.email, password },
  2116. });
  2117. }
  2118. // ============================================================
  2119. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  2120. // ============================================================
  2121. function getMailConfig(state) {
  2122. const provider = state.mailProvider || 'qq';
  2123. if (provider === '163') {
  2124. 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 邮箱' };
  2125. }
  2126. if (provider === '163-vip') {
  2127. 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 邮箱' };
  2128. }
  2129. if (provider === 'inbucket') {
  2130. const host = normalizeInbucketOrigin(state.inbucketHost);
  2131. const mailbox = (state.inbucketMailbox || '').trim();
  2132. if (!host) {
  2133. return { error: 'Inbucket 主机地址为空或无效。' };
  2134. }
  2135. if (!mailbox) {
  2136. return { error: 'Inbucket 邮箱名称为空。' };
  2137. }
  2138. return {
  2139. source: 'inbucket-mail',
  2140. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  2141. label: `Inbucket 邮箱(${mailbox})`,
  2142. navigateOnReuse: true,
  2143. inject: ['content/utils.js', 'content/inbucket-mail.js'],
  2144. injectSource: 'inbucket-mail',
  2145. };
  2146. }
  2147. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  2148. }
  2149. function normalizeInbucketOrigin(rawValue) {
  2150. const value = (rawValue || '').trim();
  2151. if (!value) return '';
  2152. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  2153. try {
  2154. const parsed = new URL(candidate);
  2155. return parsed.origin;
  2156. } catch {
  2157. return '';
  2158. }
  2159. }
  2160. function getVerificationCodeStateKey(step) {
  2161. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  2162. }
  2163. function getVerificationCodeLabel(step) {
  2164. return step === 4 ? '注册' : '登录';
  2165. }
  2166. function getVerificationPollPayload(step, state, overrides = {}) {
  2167. if (step === 4) {
  2168. return {
  2169. filterAfterTimestamp: state.flowStartTime || 0,
  2170. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  2171. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  2172. targetEmail: state.email,
  2173. maxAttempts: 5,
  2174. intervalMs: 3000,
  2175. ...overrides,
  2176. };
  2177. }
  2178. return {
  2179. filterAfterTimestamp: state.lastEmailTimestamp || state.flowStartTime || 0,
  2180. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  2181. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  2182. targetEmail: state.email,
  2183. maxAttempts: 5,
  2184. intervalMs: 3000,
  2185. ...overrides,
  2186. };
  2187. }
  2188. async function requestVerificationCodeResend(step) {
  2189. const signupTabId = await getTabId('signup-page');
  2190. if (!signupTabId) {
  2191. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  2192. }
  2193. await chrome.tabs.update(signupTabId, { active: true });
  2194. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  2195. const result = await sendToContentScript('signup-page', {
  2196. type: 'RESEND_VERIFICATION_CODE',
  2197. step,
  2198. source: 'background',
  2199. payload: {},
  2200. });
  2201. if (result && result.error) {
  2202. throw new Error(result.error);
  2203. }
  2204. return Date.now();
  2205. }
  2206. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  2207. const stateKey = getVerificationCodeStateKey(step);
  2208. const rejectedCodes = new Set();
  2209. if (state[stateKey]) {
  2210. rejectedCodes.add(state[stateKey]);
  2211. }
  2212. for (const code of (pollOverrides.excludeCodes || [])) {
  2213. if (code) rejectedCodes.add(code);
  2214. }
  2215. let lastError = null;
  2216. const filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  2217. const maxRounds = pollOverrides.maxRounds || VERIFICATION_POLL_MAX_ROUNDS;
  2218. for (let round = 1; round <= maxRounds; round++) {
  2219. if (round > 1) {
  2220. await requestVerificationCodeResend(step);
  2221. }
  2222. const payload = getVerificationPollPayload(step, state, {
  2223. ...pollOverrides,
  2224. filterAfterTimestamp,
  2225. excludeCodes: [...rejectedCodes],
  2226. });
  2227. try {
  2228. const result = await sendToMailContentScriptResilient(
  2229. mail,
  2230. {
  2231. type: 'POLL_EMAIL',
  2232. step,
  2233. source: 'background',
  2234. payload,
  2235. },
  2236. {
  2237. timeoutMs: 45000,
  2238. maxRecoveryAttempts: 2,
  2239. }
  2240. );
  2241. if (result && result.error) {
  2242. throw new Error(result.error);
  2243. }
  2244. if (!result || !result.code) {
  2245. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  2246. }
  2247. if (rejectedCodes.has(result.code)) {
  2248. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  2249. }
  2250. return result;
  2251. } catch (err) {
  2252. lastError = err;
  2253. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  2254. if (round < maxRounds) {
  2255. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  2256. }
  2257. }
  2258. }
  2259. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  2260. }
  2261. async function submitVerificationCode(step, code) {
  2262. const signupTabId = await getTabId('signup-page');
  2263. if (!signupTabId) {
  2264. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  2265. }
  2266. await chrome.tabs.update(signupTabId, { active: true });
  2267. const result = await sendToContentScript('signup-page', {
  2268. type: 'FILL_CODE',
  2269. step,
  2270. source: 'background',
  2271. payload: { code },
  2272. });
  2273. if (result && result.error) {
  2274. throw new Error(result.error);
  2275. }
  2276. return result || {};
  2277. }
  2278. async function resolveVerificationStep(step, state, mail, options = {}) {
  2279. const stateKey = getVerificationCodeStateKey(step);
  2280. const rejectedCodes = new Set();
  2281. if (state[stateKey]) {
  2282. rejectedCodes.add(state[stateKey]);
  2283. }
  2284. const nextFilterAfterTimestamp = options.filterAfterTimestamp ?? null;
  2285. const requestFreshCodeFirst = Boolean(options.requestFreshCodeFirst);
  2286. const maxSubmitAttempts = 3;
  2287. if (requestFreshCodeFirst) {
  2288. try {
  2289. await requestVerificationCodeResend(step);
  2290. await addLog(`步骤 ${step}:已先请求一封新的${getVerificationCodeLabel(step)}验证码,再开始轮询邮箱。`, 'warn');
  2291. } catch (err) {
  2292. await addLog(`步骤 ${step}:首次重新获取验证码失败:${err.message},将继续使用当前时间窗口轮询。`, 'warn');
  2293. }
  2294. }
  2295. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  2296. const result = await pollFreshVerificationCode(step, state, mail, {
  2297. excludeCodes: [...rejectedCodes],
  2298. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  2299. });
  2300. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  2301. const submitResult = await submitVerificationCode(step, result.code);
  2302. if (submitResult.invalidCode) {
  2303. rejectedCodes.add(result.code);
  2304. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  2305. if (attempt >= maxSubmitAttempts) {
  2306. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  2307. }
  2308. await requestVerificationCodeResend(step);
  2309. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  2310. continue;
  2311. }
  2312. await setState({
  2313. lastEmailTimestamp: result.emailTimestamp,
  2314. [stateKey]: result.code,
  2315. });
  2316. await completeStepFromBackground(step, {
  2317. emailTimestamp: result.emailTimestamp,
  2318. code: result.code,
  2319. });
  2320. return;
  2321. }
  2322. }
  2323. async function executeStep4(state) {
  2324. const mail = getMailConfig(state);
  2325. if (mail.error) throw new Error(mail.error);
  2326. const stepStartedAt = Date.now();
  2327. const signupTabId = await getTabId('signup-page');
  2328. if (!signupTabId) {
  2329. throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
  2330. }
  2331. await chrome.tabs.update(signupTabId, { active: true });
  2332. await addLog('步骤 4:正在确认注册验证码页面是否就绪,必要时自动恢复密码页超时报错...');
  2333. const prepareResult = await sendToContentScriptResilient(
  2334. 'signup-page',
  2335. {
  2336. type: 'PREPARE_SIGNUP_VERIFICATION',
  2337. step: 4,
  2338. source: 'background',
  2339. payload: { password: state.password || state.customPassword || '' },
  2340. },
  2341. {
  2342. timeoutMs: 30000,
  2343. retryDelayMs: 700,
  2344. logMessage: '步骤 4:认证页正在切换,等待页面重新就绪后继续检测...',
  2345. }
  2346. );
  2347. if (prepareResult && prepareResult.error) {
  2348. throw new Error(prepareResult.error);
  2349. }
  2350. if (prepareResult?.alreadyVerified) {
  2351. await completeStepFromBackground(4, {});
  2352. return;
  2353. }
  2354. await addLog(`步骤 4:正在打开${mail.label}...`);
  2355. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  2356. const alive = await isTabAlive(mail.source);
  2357. if (alive) {
  2358. if (mail.navigateOnReuse) {
  2359. await reuseOrCreateTab(mail.source, mail.url, {
  2360. inject: mail.inject,
  2361. injectSource: mail.injectSource,
  2362. });
  2363. } else {
  2364. const tabId = await getTabId(mail.source);
  2365. await chrome.tabs.update(tabId, { active: true });
  2366. }
  2367. } else {
  2368. await reuseOrCreateTab(mail.source, mail.url, {
  2369. inject: mail.inject,
  2370. injectSource: mail.injectSource,
  2371. });
  2372. }
  2373. await resolveVerificationStep(4, state, mail, {
  2374. filterAfterTimestamp: stepStartedAt,
  2375. requestFreshCodeFirst: true,
  2376. });
  2377. return;
  2378. }
  2379. // ============================================================
  2380. // Step 5: Fill Name & Birthday (via signup-page.js)
  2381. // ============================================================
  2382. async function executeStep5(state) {
  2383. const { firstName, lastName } = generateRandomName();
  2384. const { year, month, day } = generateRandomBirthday();
  2385. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  2386. await sendToContentScript('signup-page', {
  2387. type: 'EXECUTE_STEP',
  2388. step: 5,
  2389. source: 'background',
  2390. payload: { firstName, lastName, year, month, day },
  2391. });
  2392. }
  2393. // ============================================================
  2394. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  2395. // ============================================================
  2396. async function refreshOAuthUrlBeforeStep6(state) {
  2397. if (!state.vpsUrl) {
  2398. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  2399. }
  2400. await addLog('步骤 6:正在刷新登录用的 CPA OAuth 链接...');
  2401. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] preparing fresh OAuth via step 1');
  2402. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  2403. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] executing step 1 for fresh OAuth');
  2404. await executeStep1(state);
  2405. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 execute returned, waiting for completion signal');
  2406. await waitForFreshOAuth;
  2407. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 completion signal received');
  2408. const latestState = await getState();
  2409. if (!latestState.oauthUrl) {
  2410. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  2411. }
  2412. return latestState.oauthUrl;
  2413. }
  2414. async function executeStep6(state) {
  2415. if (!state.email) {
  2416. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  2417. }
  2418. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  2419. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  2420. // Reuse the signup-page tab — navigate it to the OAuth URL
  2421. await reuseOrCreateTab('signup-page', oauthUrl);
  2422. // signup-page.js will inject (same auth.openai.com domain) and handle login
  2423. await sendToContentScript('signup-page', {
  2424. type: 'EXECUTE_STEP',
  2425. step: 6,
  2426. source: 'background',
  2427. payload: { email: state.email, password: state.password },
  2428. });
  2429. }
  2430. // ============================================================
  2431. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  2432. // ============================================================
  2433. async function runStep7Attempt(state) {
  2434. const mail = getMailConfig(state);
  2435. if (mail.error) throw new Error(mail.error);
  2436. const stepStartedAt = Date.now();
  2437. const authTabId = await getTabId('signup-page');
  2438. if (authTabId) {
  2439. await chrome.tabs.update(authTabId, { active: true });
  2440. } else {
  2441. if (!state.oauthUrl) {
  2442. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  2443. }
  2444. await reuseOrCreateTab('signup-page', state.oauthUrl);
  2445. }
  2446. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  2447. const prepareResult = await sendToContentScript('signup-page', {
  2448. type: 'PREPARE_LOGIN_CODE',
  2449. step: 7,
  2450. source: 'background',
  2451. payload: {},
  2452. });
  2453. if (prepareResult && prepareResult.error) {
  2454. throw new Error(prepareResult.error);
  2455. }
  2456. await addLog(`步骤 7:正在打开${mail.label}...`);
  2457. const alive = await isTabAlive(mail.source);
  2458. if (alive) {
  2459. if (mail.navigateOnReuse) {
  2460. await reuseOrCreateTab(mail.source, mail.url, {
  2461. inject: mail.inject,
  2462. injectSource: mail.injectSource,
  2463. });
  2464. } else {
  2465. const tabId = await getTabId(mail.source);
  2466. await chrome.tabs.update(tabId, { active: true });
  2467. }
  2468. } else {
  2469. await reuseOrCreateTab(mail.source, mail.url, {
  2470. inject: mail.inject,
  2471. injectSource: mail.injectSource,
  2472. });
  2473. }
  2474. await resolveVerificationStep(7, state, mail, {
  2475. filterAfterTimestamp: stepStartedAt,
  2476. requestFreshCodeFirst: true,
  2477. });
  2478. }
  2479. async function rerunStep6ForStep7Recovery() {
  2480. const currentState = await getState();
  2481. const waitForStep6 = waitForStepComplete(6, 120000);
  2482. await addLog('步骤 7:正在回到步骤 6,重新发起登录验证码流程...', 'warn');
  2483. await executeStep6(currentState);
  2484. await waitForStep6;
  2485. await sleepWithStop(3000);
  2486. }
  2487. async function executeStep7(state) {
  2488. let lastError = null;
  2489. for (let round = 1; round <= STEP7_RESTART_MAX_ROUNDS; round++) {
  2490. const currentState = round === 1 ? state : await getState();
  2491. try {
  2492. if (round > 1) {
  2493. await addLog(`步骤 7:正在进行第 ${round}/${STEP7_RESTART_MAX_ROUNDS} 轮登录验证码恢复尝试。`, 'warn');
  2494. }
  2495. await runStep7Attempt(currentState);
  2496. return;
  2497. } catch (err) {
  2498. lastError = err;
  2499. if (!isVerificationMailPollingError(err)) {
  2500. throw err;
  2501. }
  2502. if (round >= STEP7_RESTART_MAX_ROUNDS) {
  2503. break;
  2504. }
  2505. await addLog(`步骤 7:检测到邮箱轮询类失败,准备从步骤 6 重新开始(${round + 1}/${STEP7_RESTART_MAX_ROUNDS})...`, 'warn');
  2506. await rerunStep6ForStep7Recovery();
  2507. }
  2508. }
  2509. throw lastError || new Error(`步骤 7:登录验证码流程在 ${STEP7_RESTART_MAX_ROUNDS} 轮后仍未成功。`);
  2510. }
  2511. // ============================================================
  2512. // Step 8: 完成 OAuth(自动点击 + localhost 回调监听)
  2513. // ============================================================
  2514. let webNavListener = null;
  2515. let webNavCommittedListener = null;
  2516. let step8TabUpdatedListener = null;
  2517. let step8PendingReject = null;
  2518. const STEP8_CLICK_EFFECT_TIMEOUT_MS = 3500;
  2519. const STEP8_CLICK_RETRY_DELAY_MS = 500;
  2520. const STEP8_READY_WAIT_TIMEOUT_MS = 30000;
  2521. const STEP8_SIGNUP_PAGE_INJECT_FILES = ['content/utils.js', 'content/signup-page.js'];
  2522. const STEP8_STRATEGIES = [
  2523. { mode: 'content', strategy: 'requestSubmit', label: 'form.requestSubmit' },
  2524. { mode: 'debugger', label: 'debugger click' },
  2525. { mode: 'content', strategy: 'nativeClick', label: 'element.click' },
  2526. { mode: 'content', strategy: 'dispatchClick', label: 'dispatch click' },
  2527. { mode: 'debugger', label: 'debugger click retry' },
  2528. ];
  2529. function cleanupStep8NavigationListeners() {
  2530. if (webNavListener) {
  2531. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  2532. webNavListener = null;
  2533. }
  2534. if (webNavCommittedListener) {
  2535. chrome.webNavigation.onCommitted.removeListener(webNavCommittedListener);
  2536. webNavCommittedListener = null;
  2537. }
  2538. if (step8TabUpdatedListener) {
  2539. chrome.tabs.onUpdated.removeListener(step8TabUpdatedListener);
  2540. step8TabUpdatedListener = null;
  2541. }
  2542. }
  2543. function rejectPendingStep8(error) {
  2544. if (!step8PendingReject) return;
  2545. const reject = step8PendingReject;
  2546. step8PendingReject = null;
  2547. reject(error);
  2548. }
  2549. function throwIfStep8SettledOrStopped(isSettled = false) {
  2550. if (isSettled || stopRequested) {
  2551. throw new Error(STOP_ERROR_MESSAGE);
  2552. }
  2553. }
  2554. async function ensureStep8SignupPageReady(tabId, options = {}) {
  2555. await ensureContentScriptReadyOnTab('signup-page', tabId, {
  2556. inject: STEP8_SIGNUP_PAGE_INJECT_FILES,
  2557. injectSource: 'signup-page',
  2558. timeoutMs: options.timeoutMs ?? 15000,
  2559. retryDelayMs: options.retryDelayMs ?? 600,
  2560. logMessage: options.logMessage || '',
  2561. });
  2562. }
  2563. async function getStep8PageState(tabId, responseTimeoutMs = 1500) {
  2564. try {
  2565. const result = await sendTabMessageWithTimeout(tabId, 'signup-page', {
  2566. type: 'STEP8_GET_STATE',
  2567. source: 'background',
  2568. payload: {},
  2569. }, responseTimeoutMs);
  2570. if (result?.error) {
  2571. throw new Error(result.error);
  2572. }
  2573. return result;
  2574. } catch (err) {
  2575. if (isRetryableContentScriptTransportError(err)) {
  2576. return null;
  2577. }
  2578. throw err;
  2579. }
  2580. }
  2581. async function waitForStep8Ready(tabId, timeoutMs = STEP8_READY_WAIT_TIMEOUT_MS) {
  2582. const start = Date.now();
  2583. let recovered = false;
  2584. while (Date.now() - start < timeoutMs) {
  2585. throwIfStopped();
  2586. const pageState = await getStep8PageState(tabId);
  2587. if (pageState?.addPhonePage) {
  2588. throw new Error('步骤 8:认证页进入了手机号页面,当前不是 OAuth 同意页,无法继续自动授权。');
  2589. }
  2590. if (pageState?.consentReady) {
  2591. return pageState;
  2592. }
  2593. if (pageState === null && !recovered) {
  2594. recovered = true;
  2595. await ensureStep8SignupPageReady(tabId, {
  2596. timeoutMs: Math.min(10000, timeoutMs),
  2597. logMessage: '步骤 8:认证页内容脚本已失联,正在等待页面重新就绪...',
  2598. });
  2599. continue;
  2600. }
  2601. recovered = false;
  2602. await sleepWithStop(250);
  2603. }
  2604. throw new Error('步骤 8:长时间未进入 OAuth 同意页,无法定位“继续”按钮。');
  2605. }
  2606. async function prepareStep8DebuggerClick(tabId) {
  2607. await ensureStep8SignupPageReady(tabId, {
  2608. timeoutMs: 15000,
  2609. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续定位按钮...',
  2610. });
  2611. const result = await sendToContentScriptResilient('signup-page', {
  2612. type: 'STEP8_FIND_AND_CLICK',
  2613. source: 'background',
  2614. payload: {},
  2615. }, {
  2616. timeoutMs: 15000,
  2617. retryDelayMs: 600,
  2618. logMessage: '步骤 8:认证页正在切换,等待 OAuth 同意页按钮重新就绪...',
  2619. });
  2620. if (result?.error) {
  2621. throw new Error(result.error);
  2622. }
  2623. return result;
  2624. }
  2625. async function triggerStep8ContentStrategy(tabId, strategy) {
  2626. await ensureStep8SignupPageReady(tabId, {
  2627. timeoutMs: 15000,
  2628. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续点击“继续”按钮...',
  2629. });
  2630. const result = await sendToContentScriptResilient('signup-page', {
  2631. type: 'STEP8_TRIGGER_CONTINUE',
  2632. source: 'background',
  2633. payload: {
  2634. strategy,
  2635. findTimeoutMs: 4000,
  2636. enabledTimeoutMs: 3000,
  2637. },
  2638. }, {
  2639. timeoutMs: 15000,
  2640. retryDelayMs: 600,
  2641. logMessage: '步骤 8:认证页正在切换,等待“继续”按钮重新就绪...',
  2642. });
  2643. if (result?.error) {
  2644. throw new Error(result.error);
  2645. }
  2646. return result;
  2647. }
  2648. async function waitForStep8ClickEffect(tabId, baselineUrl, timeoutMs = STEP8_CLICK_EFFECT_TIMEOUT_MS) {
  2649. const start = Date.now();
  2650. let recovered = false;
  2651. while (Date.now() - start < timeoutMs) {
  2652. throwIfStopped();
  2653. const tab = await chrome.tabs.get(tabId).catch(() => null);
  2654. if (!tab) {
  2655. throw new Error('步骤 8:认证页面标签页已关闭,无法继续自动授权。');
  2656. }
  2657. if (baselineUrl && typeof tab.url === 'string' && tab.url !== baselineUrl) {
  2658. return { progressed: true, reason: 'url_changed', url: tab.url };
  2659. }
  2660. const pageState = await getStep8PageState(tabId);
  2661. if (pageState?.addPhonePage) {
  2662. throw new Error('步骤 8:点击“继续”后页面跳到了手机号页面,当前流程无法继续自动授权。');
  2663. }
  2664. if (pageState === null) {
  2665. if (!recovered) {
  2666. recovered = true;
  2667. await ensureStep8SignupPageReady(tabId, {
  2668. timeoutMs: Math.max(3000, Math.min(8000, timeoutMs)),
  2669. logMessage: '步骤 8:点击后认证页正在重载,正在等待内容脚本重新就绪...',
  2670. }).catch(() => null);
  2671. continue;
  2672. }
  2673. return { progressed: true, reason: 'page_reloading' };
  2674. }
  2675. recovered = false;
  2676. if (pageState && !pageState.consentPage) {
  2677. return { progressed: true, reason: 'left_consent_page', url: pageState.url };
  2678. }
  2679. await sleepWithStop(200);
  2680. }
  2681. return { progressed: false, reason: 'no_effect' };
  2682. }
  2683. function getStep8EffectLabel(effect) {
  2684. switch (effect?.reason) {
  2685. case 'url_changed':
  2686. return `URL 已变化:${effect.url}`;
  2687. case 'page_reloading':
  2688. return '页面正在跳转或重载';
  2689. case 'left_consent_page':
  2690. return `页面已离开 OAuth 同意页:${effect.url || 'unknown'}`;
  2691. default:
  2692. return '页面仍停留在 OAuth 同意页';
  2693. }
  2694. }
  2695. async function executeStep8(state) {
  2696. if (!state.oauthUrl) {
  2697. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  2698. }
  2699. await addLog('步骤 8:正在监听 localhost 回调地址...');
  2700. return new Promise((resolve, reject) => {
  2701. let resolved = false;
  2702. let signupTabId = null;
  2703. const cleanupListener = () => {
  2704. cleanupStep8NavigationListeners();
  2705. step8PendingReject = null;
  2706. };
  2707. const rejectStep8 = (error) => {
  2708. if (resolved) return;
  2709. resolved = true;
  2710. clearTimeout(timeout);
  2711. cleanupListener();
  2712. reject(error);
  2713. };
  2714. const finalizeStep8Callback = (callbackUrl) => {
  2715. if (resolved || !callbackUrl) return;
  2716. resolved = true;
  2717. cleanupListener();
  2718. clearTimeout(timeout);
  2719. addLog(`步骤 8:已捕获 localhost 地址:${callbackUrl}`, 'ok').then(() => {
  2720. return completeStepFromBackground(8, { localhostUrl: callbackUrl });
  2721. }).then(() => {
  2722. resolve();
  2723. }).catch((err) => {
  2724. reject(err);
  2725. });
  2726. };
  2727. const timeout = setTimeout(() => {
  2728. rejectStep8(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  2729. }, 120000);
  2730. step8PendingReject = (error) => {
  2731. rejectStep8(error);
  2732. };
  2733. webNavListener = (details) => {
  2734. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  2735. finalizeStep8Callback(callbackUrl);
  2736. };
  2737. webNavCommittedListener = (details) => {
  2738. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  2739. finalizeStep8Callback(callbackUrl);
  2740. };
  2741. step8TabUpdatedListener = (tabId, changeInfo, tab) => {
  2742. const callbackUrl = getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId);
  2743. finalizeStep8Callback(callbackUrl);
  2744. };
  2745. (async () => {
  2746. try {
  2747. throwIfStep8SettledOrStopped(resolved);
  2748. signupTabId = await getTabId('signup-page');
  2749. throwIfStep8SettledOrStopped(resolved);
  2750. if (signupTabId && await isTabAlive('signup-page')) {
  2751. await chrome.tabs.update(signupTabId, { active: true });
  2752. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  2753. } else {
  2754. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  2755. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  2756. }
  2757. throwIfStep8SettledOrStopped(resolved);
  2758. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  2759. chrome.webNavigation.onCommitted.addListener(webNavCommittedListener);
  2760. chrome.tabs.onUpdated.addListener(step8TabUpdatedListener);
  2761. await ensureStep8SignupPageReady(signupTabId, {
  2762. timeoutMs: 15000,
  2763. logMessage: '步骤 8:认证页内容脚本尚未就绪,正在等待页面恢复...',
  2764. });
  2765. let attempt = 0;
  2766. while (!resolved) {
  2767. throwIfStep8SettledOrStopped(resolved);
  2768. const pageState = await waitForStep8Ready(signupTabId);
  2769. if (!pageState?.consentReady) {
  2770. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  2771. continue;
  2772. }
  2773. const strategy = STEP8_STRATEGIES[attempt % STEP8_STRATEGIES.length];
  2774. const round = attempt + 1;
  2775. attempt += 1;
  2776. await addLog(`步骤 8:第 ${round} 次尝试点击“继续”(${strategy.label})...`);
  2777. if (strategy.mode === 'debugger') {
  2778. const clickTarget = await prepareStep8DebuggerClick(signupTabId);
  2779. throwIfStep8SettledOrStopped(resolved);
  2780. await clickWithDebugger(signupTabId, clickTarget?.rect);
  2781. } else {
  2782. await triggerStep8ContentStrategy(signupTabId, strategy.strategy);
  2783. }
  2784. if (resolved) {
  2785. return;
  2786. }
  2787. const effect = await waitForStep8ClickEffect(signupTabId, pageState.url);
  2788. if (resolved) {
  2789. return;
  2790. }
  2791. if (effect.progressed) {
  2792. await addLog(`步骤 8:检测到本次点击已生效,${getStep8EffectLabel(effect)},继续等待 localhost 回调...`, 'info');
  2793. break;
  2794. }
  2795. await addLog(`步骤 8:${strategy.label} 本次未触发页面离开同意页,准备继续重试。`, 'warn');
  2796. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  2797. }
  2798. } catch (err) {
  2799. rejectStep8(err);
  2800. }
  2801. })();
  2802. });
  2803. }
  2804. // ============================================================
  2805. // Step 9: CPA 回调验证(通过 vps-panel.js)
  2806. // ============================================================
  2807. async function executeStep9(state) {
  2808. if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
  2809. throw new Error('步骤 8 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 8。');
  2810. }
  2811. if (!state.localhostUrl) {
  2812. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  2813. }
  2814. if (!state.vpsUrl) {
  2815. throw new Error('尚未填写 CPA 地址,请先在侧边栏输入。');
  2816. }
  2817. if (shouldBypassStep9ForLocalCpa(state)) {
  2818. await addLog('步骤 9:检测到本地 CPA,步骤 8 完成后已自动添加,无需重复提交回调地址。', 'info');
  2819. await completeStepFromBackground(9, {
  2820. localhostUrl: state.localhostUrl,
  2821. verifiedStatus: 'local-auto',
  2822. });
  2823. return;
  2824. }
  2825. await addLog('步骤 9:正在打开 CPA 面板...');
  2826. const injectFiles = ['content/utils.js', 'content/vps-panel.js'];
  2827. let tabId = await getTabId('vps-panel');
  2828. const alive = tabId && await isTabAlive('vps-panel');
  2829. if (!alive) {
  2830. tabId = await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  2831. inject: injectFiles,
  2832. reloadIfSameUrl: true,
  2833. });
  2834. } else {
  2835. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  2836. await chrome.tabs.update(tabId, { active: true });
  2837. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  2838. }
  2839. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  2840. inject: injectFiles,
  2841. });
  2842. await addLog('步骤 9:正在填写回调地址...');
  2843. const result = await sendToContentScriptResilient('vps-panel', {
  2844. type: 'EXECUTE_STEP',
  2845. step: 9,
  2846. source: 'background',
  2847. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  2848. }, {
  2849. timeoutMs: 30000,
  2850. retryDelayMs: 700,
  2851. logMessage: '步骤 9:CPA 面板通信未就绪,正在等待页面恢复...',
  2852. });
  2853. if (result?.error) {
  2854. throw new Error(result.error);
  2855. }
  2856. }
  2857. // ============================================================
  2858. // Open Side Panel on extension icon click
  2859. // ============================================================
  2860. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
  2861. chrome.alarms.onAlarm.addListener((alarm) => {
  2862. if (alarm.name !== AUTO_RUN_ALARM_NAME) {
  2863. return;
  2864. }
  2865. launchScheduledAutoRun('alarm').catch((err) => {
  2866. console.error(LOG_PREFIX, 'Failed to launch scheduled auto run from alarm:', err);
  2867. });
  2868. });
  2869. chrome.runtime.onStartup.addListener(() => {
  2870. restoreScheduledAutoRunIfNeeded().catch((err) => {
  2871. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on startup:', err);
  2872. });
  2873. });
  2874. chrome.runtime.onInstalled.addListener(() => {
  2875. restoreScheduledAutoRunIfNeeded().catch((err) => {
  2876. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on install/update:', err);
  2877. });
  2878. });
  2879. restoreScheduledAutoRunIfNeeded().catch((err) => {
  2880. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run:', err);
  2881. });