background.js 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444
  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. const STEP7_RESTART_FROM_STEP6_ERROR_CODE = 'STEP7_RESTART_FROM_STEP6';
  870. function createStep7RestartFromStep6Error(details = {}) {
  871. const { reason = 'unknown', url = '' } = details || {};
  872. const reasonLabel = reason === 'login_timeout_error_page'
  873. ? '检测到登录页超时报错'
  874. : '步骤 7 请求回到步骤 6';
  875. const error = new Error(`步骤 7:${reasonLabel}。${url ? `URL: ${url}` : ''}`.trim());
  876. error.code = STEP7_RESTART_FROM_STEP6_ERROR_CODE;
  877. error.restartReason = reason;
  878. error.restartUrl = url;
  879. return error;
  880. }
  881. function getStep7RestartFromStep6Error(result) {
  882. if (!result?.restartFromStep6) {
  883. return null;
  884. }
  885. return createStep7RestartFromStep6Error(result);
  886. }
  887. function isStep7RestartFromStep6Error(error) {
  888. return error?.code === STEP7_RESTART_FROM_STEP6_ERROR_CODE;
  889. }
  890. function isStep7RecoverableError(error) {
  891. return isVerificationMailPollingError(error) || isStep7RestartFromStep6Error(error);
  892. }
  893. function isRestartCurrentAttemptError(error) {
  894. const message = String(typeof error === 'string' ? error : error?.message || '');
  895. return /当前邮箱已存在,需要重新开始新一轮/.test(message);
  896. }
  897. function isStep9OAuthTimeoutError(error) {
  898. const message = String(typeof error === 'string' ? error : error?.message || '');
  899. return /STEP9_OAUTH_TIMEOUT::|认证失败:\s*Timeout waiting for OAuth callback/i.test(message);
  900. }
  901. function isStepDoneStatus(status) {
  902. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  903. }
  904. function getFirstUnfinishedStep(statuses = {}) {
  905. for (let step = 1; step <= 9; step++) {
  906. if (!isStepDoneStatus(statuses[step] || 'pending')) {
  907. return step;
  908. }
  909. }
  910. return null;
  911. }
  912. function hasSavedProgress(statuses = {}) {
  913. return Object.values({ ...DEFAULT_STATE.stepStatuses, ...statuses }).some((status) => status !== 'pending');
  914. }
  915. function getDownstreamStateResets(step) {
  916. if (step <= 1) {
  917. return {
  918. oauthUrl: null,
  919. flowStartTime: null,
  920. password: null,
  921. lastEmailTimestamp: null,
  922. lastSignupCode: null,
  923. lastLoginCode: null,
  924. localhostUrl: null,
  925. };
  926. }
  927. if (step === 2) {
  928. return {
  929. password: null,
  930. lastEmailTimestamp: null,
  931. lastSignupCode: null,
  932. lastLoginCode: null,
  933. localhostUrl: null,
  934. };
  935. }
  936. if (step === 3 || step === 4) {
  937. return {
  938. lastEmailTimestamp: null,
  939. lastSignupCode: null,
  940. lastLoginCode: null,
  941. localhostUrl: null,
  942. };
  943. }
  944. if (step === 5 || step === 6 || step === 7) {
  945. return {
  946. lastLoginCode: null,
  947. localhostUrl: null,
  948. };
  949. }
  950. if (step === 8) {
  951. return {
  952. localhostUrl: null,
  953. };
  954. }
  955. return {};
  956. }
  957. async function invalidateDownstreamAfterStepRestart(step, options = {}) {
  958. const { logLabel = `步骤 ${step} 重新执行` } = options;
  959. const state = await getState();
  960. const statuses = { ...(state.stepStatuses || {}) };
  961. const changedSteps = [];
  962. for (let downstream = step + 1; downstream <= 9; downstream++) {
  963. if (statuses[downstream] !== 'pending') {
  964. statuses[downstream] = 'pending';
  965. changedSteps.push(downstream);
  966. }
  967. }
  968. if (changedSteps.length) {
  969. await setState({ stepStatuses: statuses });
  970. for (const downstream of changedSteps) {
  971. chrome.runtime.sendMessage({
  972. type: 'STEP_STATUS_CHANGED',
  973. payload: { step: downstream, status: 'pending' },
  974. }).catch(() => { });
  975. }
  976. await addLog(`${logLabel},已重置后续步骤状态:${changedSteps.join(', ')}`, 'warn');
  977. }
  978. const resets = getDownstreamStateResets(step);
  979. if (Object.keys(resets).length) {
  980. await setState(resets);
  981. broadcastDataUpdate(resets);
  982. }
  983. }
  984. function clearStopRequest() {
  985. stopRequested = false;
  986. }
  987. function getAutoRunStatusPayload(phase, payload = {}) {
  988. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  989. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  990. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  991. const rawScheduledAt = phase === 'scheduled'
  992. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  993. : null;
  994. const scheduledAt = rawScheduledAt === null ? null : Number(rawScheduledAt);
  995. const autoRunning = phase === 'scheduled' || phase === 'running' || phase === 'waiting_email' || phase === 'retrying';
  996. return {
  997. autoRunning,
  998. autoRunPhase: phase,
  999. autoRunCurrentRun: currentRun,
  1000. autoRunTotalRuns: totalRuns,
  1001. autoRunAttemptRun: attemptRun,
  1002. scheduledAutoRunAt: Number.isFinite(scheduledAt) ? scheduledAt : null,
  1003. };
  1004. }
  1005. async function broadcastAutoRunStatus(phase, payload = {}, extraState = {}) {
  1006. const rawScheduledAt = phase === 'scheduled'
  1007. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  1008. : null;
  1009. const statusPayload = {
  1010. phase,
  1011. currentRun: payload.currentRun ?? autoRunCurrentRun,
  1012. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  1013. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  1014. scheduledAt: rawScheduledAt === null ? null : Number(rawScheduledAt),
  1015. };
  1016. await setState({
  1017. ...extraState,
  1018. ...getAutoRunStatusPayload(phase, statusPayload),
  1019. });
  1020. chrome.runtime.sendMessage({
  1021. type: 'AUTO_RUN_STATUS',
  1022. payload: statusPayload,
  1023. }).catch(() => { });
  1024. }
  1025. function isAutoRunLockedState(state) {
  1026. return Boolean(state.autoRunning) && (state.autoRunPhase === 'running' || state.autoRunPhase === 'retrying');
  1027. }
  1028. function isAutoRunPausedState(state) {
  1029. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  1030. }
  1031. function isAutoRunScheduledState(state) {
  1032. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  1033. return Boolean(state.autoRunning)
  1034. && state.autoRunPhase === 'scheduled'
  1035. && Number.isFinite(scheduledAt)
  1036. && Boolean(normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan));
  1037. }
  1038. function formatAutoRunScheduleTime(timestamp) {
  1039. return new Date(timestamp).toLocaleString('zh-CN', {
  1040. hour12: false,
  1041. month: '2-digit',
  1042. day: '2-digit',
  1043. hour: '2-digit',
  1044. minute: '2-digit',
  1045. second: '2-digit',
  1046. });
  1047. }
  1048. async function setAutoRunDelayEnabledState(enabled) {
  1049. const normalized = Boolean(enabled);
  1050. await setPersistentSettings({ autoRunDelayEnabled: normalized });
  1051. await setState({ autoRunDelayEnabled: normalized });
  1052. broadcastDataUpdate({ autoRunDelayEnabled: normalized });
  1053. }
  1054. async function ensureScheduledAutoRunAlarm(scheduledAt) {
  1055. if (!Number.isFinite(scheduledAt) || scheduledAt <= Date.now()) {
  1056. return false;
  1057. }
  1058. const existingAlarm = await chrome.alarms.get(AUTO_RUN_ALARM_NAME);
  1059. if (!existingAlarm || Math.abs((existingAlarm.scheduledTime || 0) - scheduledAt) > 1000) {
  1060. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  1061. await chrome.alarms.create(AUTO_RUN_ALARM_NAME, { when: scheduledAt });
  1062. }
  1063. return true;
  1064. }
  1065. async function clearScheduledAutoRunAlarm() {
  1066. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  1067. }
  1068. async function scheduleAutoRun(totalRuns, options = {}) {
  1069. const state = await getState();
  1070. if (isAutoRunLockedState(state) || isAutoRunPausedState(state) || autoRunActive) {
  1071. throw new Error('自动运行已在进行中,请先停止后再重新计划。');
  1072. }
  1073. if (isAutoRunScheduledState(state)) {
  1074. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  1075. }
  1076. const delayMinutes = normalizeAutoRunDelayMinutes(options.delayMinutes);
  1077. const plan = normalizeScheduledAutoRunPlan({
  1078. totalRuns,
  1079. autoRunSkipFailures: options.autoRunSkipFailures,
  1080. mode: options.mode,
  1081. });
  1082. const scheduledAt = Date.now() + delayMinutes * 60 * 1000;
  1083. autoRunCurrentRun = 0;
  1084. autoRunTotalRuns = plan.totalRuns;
  1085. autoRunAttemptRun = 0;
  1086. await ensureScheduledAutoRunAlarm(scheduledAt);
  1087. await broadcastAutoRunStatus(
  1088. 'scheduled',
  1089. {
  1090. currentRun: 0,
  1091. totalRuns: plan.totalRuns,
  1092. attemptRun: 0,
  1093. scheduledAt,
  1094. },
  1095. {
  1096. autoRunSkipFailures: plan.autoRunSkipFailures,
  1097. scheduledAutoRunPlan: plan,
  1098. }
  1099. );
  1100. await addLog(
  1101. `自动运行已计划:${delayMinutes} 分钟后启动(${formatAutoRunScheduleTime(scheduledAt)}),目标 ${plan.totalRuns} 轮。`,
  1102. 'info'
  1103. );
  1104. return { ok: true, scheduledAt };
  1105. }
  1106. let scheduledAutoRunLaunching = false;
  1107. async function launchScheduledAutoRun(trigger = 'alarm') {
  1108. if (scheduledAutoRunLaunching) {
  1109. return false;
  1110. }
  1111. scheduledAutoRunLaunching = true;
  1112. try {
  1113. const state = await getState();
  1114. if (!isAutoRunScheduledState(state)) {
  1115. return false;
  1116. }
  1117. if (autoRunActive) {
  1118. return false;
  1119. }
  1120. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1121. if (!plan) {
  1122. await clearScheduledAutoRunAlarm();
  1123. await broadcastAutoRunStatus('idle', {
  1124. currentRun: 0,
  1125. totalRuns: 1,
  1126. attemptRun: 0,
  1127. }, {
  1128. scheduledAutoRunPlan: null,
  1129. });
  1130. return false;
  1131. }
  1132. await clearScheduledAutoRunAlarm();
  1133. if (trigger !== 'manual' && state.autoRunDelayEnabled) {
  1134. await setAutoRunDelayEnabledState(false);
  1135. }
  1136. await broadcastAutoRunStatus(
  1137. 'running',
  1138. {
  1139. currentRun: 0,
  1140. totalRuns: plan.totalRuns,
  1141. attemptRun: 0,
  1142. },
  1143. {
  1144. autoRunSkipFailures: plan.autoRunSkipFailures,
  1145. scheduledAutoRunPlan: null,
  1146. }
  1147. );
  1148. clearStopRequest();
  1149. await addLog(
  1150. trigger === 'manual'
  1151. ? '已手动跳过倒计时,自动运行立即开始。'
  1152. : '倒计时结束,自动运行开始执行。',
  1153. 'info'
  1154. );
  1155. autoRunLoop(plan.totalRuns, {
  1156. autoRunSkipFailures: plan.autoRunSkipFailures,
  1157. mode: plan.mode,
  1158. });
  1159. return true;
  1160. } finally {
  1161. scheduledAutoRunLaunching = false;
  1162. }
  1163. }
  1164. async function cancelScheduledAutoRun(options = {}) {
  1165. const state = await getState();
  1166. if (!isAutoRunScheduledState(state)) {
  1167. return false;
  1168. }
  1169. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1170. await clearScheduledAutoRunAlarm();
  1171. autoRunCurrentRun = 0;
  1172. autoRunTotalRuns = plan?.totalRuns || 1;
  1173. autoRunAttemptRun = 0;
  1174. await broadcastAutoRunStatus(
  1175. 'idle',
  1176. {
  1177. currentRun: 0,
  1178. totalRuns: plan?.totalRuns || 1,
  1179. attemptRun: 0,
  1180. },
  1181. {
  1182. scheduledAutoRunPlan: null,
  1183. }
  1184. );
  1185. if (options.logMessage !== false) {
  1186. await addLog(options.logMessage || '已取消自动运行倒计时计划。', 'warn');
  1187. }
  1188. return true;
  1189. }
  1190. async function restoreScheduledAutoRunIfNeeded() {
  1191. const state = await getState();
  1192. if (state.autoRunPhase !== 'scheduled') {
  1193. return;
  1194. }
  1195. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1196. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  1197. if (!plan || !Number.isFinite(scheduledAt)) {
  1198. await clearScheduledAutoRunAlarm();
  1199. await broadcastAutoRunStatus('idle', {
  1200. currentRun: 0,
  1201. totalRuns: 1,
  1202. attemptRun: 0,
  1203. }, {
  1204. scheduledAutoRunPlan: null,
  1205. });
  1206. return;
  1207. }
  1208. if (scheduledAt <= Date.now()) {
  1209. await launchScheduledAutoRun('restore');
  1210. return;
  1211. }
  1212. await ensureScheduledAutoRunAlarm(scheduledAt);
  1213. }
  1214. async function ensureManualInteractionAllowed(actionLabel) {
  1215. const state = await getState();
  1216. if (isAutoRunLockedState(state)) {
  1217. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  1218. }
  1219. if (isAutoRunPausedState(state)) {
  1220. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  1221. }
  1222. if (isAutoRunScheduledState(state)) {
  1223. throw new Error(`自动流程已计划启动。请先取消计划,或立即开始后再${actionLabel}。`);
  1224. }
  1225. return state;
  1226. }
  1227. async function skipStep(step) {
  1228. const state = await ensureManualInteractionAllowed('跳过步骤');
  1229. if (!Number.isInteger(step) || step < 1 || step > 9) {
  1230. throw new Error(`无效步骤:${step}`);
  1231. }
  1232. const statuses = { ...(state.stepStatuses || {}) };
  1233. const currentStatus = statuses[step];
  1234. if (currentStatus === 'running') {
  1235. throw new Error(`步骤 ${step} 正在运行中,不能跳过。`);
  1236. }
  1237. if (isStepDoneStatus(currentStatus)) {
  1238. throw new Error(`步骤 ${step} 已完成,无需再跳过。`);
  1239. }
  1240. if (step > 1) {
  1241. const prevStatus = statuses[step - 1];
  1242. if (!isStepDoneStatus(prevStatus)) {
  1243. throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`);
  1244. }
  1245. }
  1246. await setStepStatus(step, 'skipped');
  1247. await addLog(`步骤 ${step} 已跳过`, 'warn');
  1248. if (step === 1) {
  1249. const latestState = await getState();
  1250. const step2Status = latestState.stepStatuses?.[2];
  1251. if (!isStepDoneStatus(step2Status) && step2Status !== 'running') {
  1252. await setStepStatus(2, 'skipped');
  1253. await addLog('步骤 1 已跳过,步骤 2 也已同时跳过。', 'warn');
  1254. }
  1255. }
  1256. return { ok: true, step, status: 'skipped' };
  1257. }
  1258. function throwIfStopped() {
  1259. if (stopRequested) {
  1260. throw new Error(STOP_ERROR_MESSAGE);
  1261. }
  1262. }
  1263. async function sleepWithStop(ms) {
  1264. const start = Date.now();
  1265. while (Date.now() - start < ms) {
  1266. throwIfStopped();
  1267. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  1268. }
  1269. }
  1270. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  1271. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  1272. await sleepWithStop(duration);
  1273. }
  1274. async function clickWithDebugger(tabId, rect) {
  1275. if (!tabId) {
  1276. throw new Error('未找到用于调试点击的认证页面标签页。');
  1277. }
  1278. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  1279. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  1280. }
  1281. const target = { tabId };
  1282. try {
  1283. await chrome.debugger.attach(target, '1.3');
  1284. } catch (err) {
  1285. throw new Error(
  1286. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  1287. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  1288. );
  1289. }
  1290. try {
  1291. const x = Math.round(rect.centerX);
  1292. const y = Math.round(rect.centerY);
  1293. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  1294. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1295. type: 'mouseMoved',
  1296. x,
  1297. y,
  1298. button: 'none',
  1299. buttons: 0,
  1300. clickCount: 0,
  1301. });
  1302. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1303. type: 'mousePressed',
  1304. x,
  1305. y,
  1306. button: 'left',
  1307. buttons: 1,
  1308. clickCount: 1,
  1309. });
  1310. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1311. type: 'mouseReleased',
  1312. x,
  1313. y,
  1314. button: 'left',
  1315. buttons: 0,
  1316. clickCount: 1,
  1317. });
  1318. } finally {
  1319. await chrome.debugger.detach(target).catch(() => { });
  1320. }
  1321. }
  1322. async function broadcastStopToContentScripts() {
  1323. const registry = await getTabRegistry();
  1324. for (const entry of Object.values(registry)) {
  1325. if (!entry?.tabId) continue;
  1326. try {
  1327. await chrome.tabs.sendMessage(entry.tabId, {
  1328. type: 'STOP_FLOW',
  1329. source: 'background',
  1330. payload: {},
  1331. });
  1332. } catch { }
  1333. }
  1334. }
  1335. let stopRequested = false;
  1336. // ============================================================
  1337. // Message Handler (central router)
  1338. // ============================================================
  1339. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  1340. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  1341. handleMessage(message, sender).then(response => {
  1342. sendResponse(response);
  1343. }).catch(err => {
  1344. console.error(LOG_PREFIX, 'Handler error:', err);
  1345. sendResponse({ error: err.message });
  1346. });
  1347. return true; // async response
  1348. });
  1349. async function handleMessage(message, sender) {
  1350. switch (message.type) {
  1351. case 'CONTENT_SCRIPT_READY': {
  1352. const tabId = sender.tab?.id;
  1353. if (tabId && message.source) {
  1354. await registerTab(message.source, tabId);
  1355. flushCommand(message.source, tabId);
  1356. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  1357. }
  1358. return { ok: true };
  1359. }
  1360. case 'LOG': {
  1361. const { message: msg, level } = message.payload;
  1362. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  1363. return { ok: true };
  1364. }
  1365. case 'STEP_COMPLETE': {
  1366. if (stopRequested) {
  1367. await setStepStatus(message.step, 'stopped');
  1368. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  1369. return { ok: true };
  1370. }
  1371. await setStepStatus(message.step, 'completed');
  1372. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  1373. await handleStepData(message.step, message.payload);
  1374. notifyStepComplete(message.step, message.payload);
  1375. return { ok: true };
  1376. }
  1377. case 'STEP_ERROR': {
  1378. if (isStopError(message.error)) {
  1379. await setStepStatus(message.step, 'stopped');
  1380. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  1381. notifyStepError(message.step, message.error);
  1382. } else {
  1383. await setStepStatus(message.step, 'failed');
  1384. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  1385. notifyStepError(message.step, message.error);
  1386. }
  1387. return { ok: true };
  1388. }
  1389. case 'GET_STATE': {
  1390. return await getState();
  1391. }
  1392. case 'RESET': {
  1393. clearStopRequest();
  1394. await clearScheduledAutoRunAlarm();
  1395. await resetState();
  1396. await addLog('流程已重置', 'info');
  1397. return { ok: true };
  1398. }
  1399. case 'EXECUTE_STEP': {
  1400. clearStopRequest();
  1401. if (message.source === 'sidepanel') {
  1402. await ensureManualInteractionAllowed('手动执行步骤');
  1403. }
  1404. const step = message.payload.step;
  1405. if (message.source === 'sidepanel') {
  1406. await invalidateDownstreamAfterStepRestart(step, { logLabel: `步骤 ${step} 重新执行` });
  1407. }
  1408. // Save email if provided (from side panel step 3)
  1409. if (message.payload.email) {
  1410. await setEmailState(message.payload.email);
  1411. }
  1412. await executeStep(step);
  1413. return { ok: true };
  1414. }
  1415. case 'AUTO_RUN': {
  1416. clearStopRequest();
  1417. const state = await getState();
  1418. if (isAutoRunScheduledState(state)) {
  1419. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  1420. }
  1421. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  1422. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  1423. const mode = message.payload?.mode === 'continue' ? 'continue' : 'restart';
  1424. await setState({ autoRunSkipFailures });
  1425. autoRunLoop(totalRuns, { autoRunSkipFailures, mode }); // fire-and-forget
  1426. return { ok: true };
  1427. }
  1428. case 'SCHEDULE_AUTO_RUN': {
  1429. clearStopRequest();
  1430. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  1431. return await scheduleAutoRun(totalRuns, {
  1432. delayMinutes: message.payload?.delayMinutes,
  1433. autoRunSkipFailures: Boolean(message.payload?.autoRunSkipFailures),
  1434. mode: message.payload?.mode,
  1435. });
  1436. }
  1437. case 'START_SCHEDULED_AUTO_RUN_NOW': {
  1438. clearStopRequest();
  1439. const started = await launchScheduledAutoRun('manual');
  1440. if (!started) {
  1441. throw new Error('当前没有可立即开始的倒计时计划。');
  1442. }
  1443. return { ok: true };
  1444. }
  1445. case 'CANCEL_SCHEDULED_AUTO_RUN': {
  1446. const cancelled = await cancelScheduledAutoRun();
  1447. if (!cancelled) {
  1448. throw new Error('当前没有可取消的倒计时计划。');
  1449. }
  1450. return { ok: true };
  1451. }
  1452. case 'RESUME_AUTO_RUN': {
  1453. clearStopRequest();
  1454. if (message.payload.email) {
  1455. await setEmailState(message.payload.email);
  1456. }
  1457. resumeAutoRun(); // fire-and-forget
  1458. return { ok: true };
  1459. }
  1460. case 'TAKEOVER_AUTO_RUN': {
  1461. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  1462. await addLog('自动流程已切换为手动控制。', 'warn');
  1463. return { ok: true };
  1464. }
  1465. case 'SKIP_STEP': {
  1466. const step = Number(message.payload?.step);
  1467. return await skipStep(step);
  1468. }
  1469. case 'SAVE_SETTING': {
  1470. const updates = {};
  1471. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  1472. if (message.payload.vpsPassword !== undefined) updates.vpsPassword = message.payload.vpsPassword;
  1473. if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
  1474. if (message.payload.autoRunSkipFailures !== undefined) updates.autoRunSkipFailures = Boolean(message.payload.autoRunSkipFailures);
  1475. if (message.payload.autoRunDelayEnabled !== undefined) updates.autoRunDelayEnabled = Boolean(message.payload.autoRunDelayEnabled);
  1476. if (message.payload.autoRunDelayMinutes !== undefined) updates.autoRunDelayMinutes = normalizeAutoRunDelayMinutes(message.payload.autoRunDelayMinutes);
  1477. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  1478. if (message.payload.inbucketHost !== undefined) updates.inbucketHost = message.payload.inbucketHost;
  1479. if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
  1480. await setPersistentSettings(updates);
  1481. await setState(updates);
  1482. return { ok: true };
  1483. }
  1484. // Side panel data updates
  1485. case 'SAVE_EMAIL': {
  1486. const state = await getState();
  1487. if (isAutoRunLockedState(state)) {
  1488. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  1489. }
  1490. await setEmailState(message.payload.email);
  1491. await resumeAutoRun();
  1492. return { ok: true, email: message.payload.email };
  1493. }
  1494. case 'FETCH_DUCK_EMAIL': {
  1495. clearStopRequest();
  1496. const state = await getState();
  1497. if (isAutoRunLockedState(state)) {
  1498. throw new Error('自动流程运行中,当前不能手动获取 Duck 邮箱。');
  1499. }
  1500. const email = await fetchDuckEmail(message.payload || {});
  1501. await resumeAutoRun();
  1502. return { ok: true, email };
  1503. }
  1504. case 'STOP_FLOW': {
  1505. await requestStop();
  1506. return { ok: true };
  1507. }
  1508. default:
  1509. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  1510. return { error: `Unknown message type: ${message.type}` };
  1511. }
  1512. }
  1513. // ============================================================
  1514. // Step Data Handlers
  1515. // ============================================================
  1516. async function handleStepData(step, payload) {
  1517. switch (step) {
  1518. case 1:
  1519. if (payload.oauthUrl) {
  1520. await setState({ oauthUrl: payload.oauthUrl });
  1521. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  1522. }
  1523. break;
  1524. case 3:
  1525. if (payload.email) await setEmailState(payload.email);
  1526. break;
  1527. case 4:
  1528. if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
  1529. break;
  1530. case 8:
  1531. if (payload.localhostUrl) {
  1532. if (!isLocalhostOAuthCallbackUrl(payload.localhostUrl)) {
  1533. throw new Error('步骤 8 返回了无效的 localhost OAuth 回调地址。');
  1534. }
  1535. await setState({ localhostUrl: payload.localhostUrl });
  1536. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  1537. }
  1538. break;
  1539. case 9: {
  1540. if (payload.localhostUrl) {
  1541. await closeLocalhostCallbackTabs(payload.localhostUrl);
  1542. }
  1543. break;
  1544. }
  1545. }
  1546. }
  1547. // ============================================================
  1548. // Step Completion Waiting
  1549. // ============================================================
  1550. // Map of step -> { resolve, reject } for waiting on step completion
  1551. const stepWaiters = new Map();
  1552. let resumeWaiter = null;
  1553. const AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS = 120000;
  1554. const AUTO_RUN_BACKGROUND_COMPLETED_STEPS = new Set([4, 7, 8]);
  1555. function waitForStepComplete(step, timeoutMs = 120000) {
  1556. return new Promise((resolve, reject) => {
  1557. throwIfStopped();
  1558. if (stepWaiters.has(step)) {
  1559. console.warn(LOG_PREFIX, `[waitForStepComplete] replacing existing waiter for step ${step}`);
  1560. }
  1561. console.log(LOG_PREFIX, `[waitForStepComplete] register step ${step}, timeout=${timeoutMs}ms`);
  1562. const timer = setTimeout(() => {
  1563. stepWaiters.delete(step);
  1564. console.warn(LOG_PREFIX, `[waitForStepComplete] timeout for step ${step} after ${timeoutMs}ms`);
  1565. reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
  1566. }, timeoutMs);
  1567. stepWaiters.set(step, {
  1568. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  1569. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  1570. });
  1571. });
  1572. }
  1573. function notifyStepComplete(step, payload) {
  1574. const waiter = stepWaiters.get(step);
  1575. console.log(LOG_PREFIX, `[notifyStepComplete] step ${step}, hasWaiter=${Boolean(waiter)}`);
  1576. if (waiter) waiter.resolve(payload);
  1577. }
  1578. function notifyStepError(step, error) {
  1579. const waiter = stepWaiters.get(step);
  1580. console.warn(LOG_PREFIX, `[notifyStepError] step ${step}, hasWaiter=${Boolean(waiter)}, error=${error}`);
  1581. if (waiter) waiter.reject(new Error(error));
  1582. }
  1583. async function completeStepFromBackground(step, payload = {}) {
  1584. if (stopRequested) {
  1585. await setStepStatus(step, 'stopped');
  1586. notifyStepError(step, STOP_ERROR_MESSAGE);
  1587. return;
  1588. }
  1589. await setStepStatus(step, 'completed');
  1590. await addLog(`步骤 ${step} 已完成`, 'ok');
  1591. await handleStepData(step, payload);
  1592. notifyStepComplete(step, payload);
  1593. }
  1594. async function markRunningStepsStopped() {
  1595. const state = await getState();
  1596. const runningSteps = Object.entries(state.stepStatuses || {})
  1597. .filter(([, status]) => status === 'running')
  1598. .map(([step]) => Number(step));
  1599. for (const step of runningSteps) {
  1600. await setStepStatus(step, 'stopped');
  1601. }
  1602. }
  1603. async function requestStop(options = {}) {
  1604. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  1605. const state = await getState();
  1606. if (isAutoRunScheduledState(state) && !autoRunActive) {
  1607. await cancelScheduledAutoRun({
  1608. logMessage: options.logMessage === false
  1609. ? false
  1610. : (options.logMessage || '已取消自动运行倒计时计划。'),
  1611. });
  1612. return;
  1613. }
  1614. if (stopRequested) return;
  1615. stopRequested = true;
  1616. cancelPendingCommands();
  1617. cleanupStep8NavigationListeners();
  1618. rejectPendingStep8(new Error(STOP_ERROR_MESSAGE));
  1619. await addLog(logMessage, 'warn');
  1620. await broadcastStopToContentScripts();
  1621. for (const waiter of stepWaiters.values()) {
  1622. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  1623. }
  1624. stepWaiters.clear();
  1625. if (resumeWaiter) {
  1626. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  1627. resumeWaiter = null;
  1628. }
  1629. await markRunningStepsStopped();
  1630. autoRunActive = false;
  1631. await broadcastAutoRunStatus('stopped', {
  1632. currentRun: autoRunCurrentRun,
  1633. totalRuns: autoRunTotalRuns,
  1634. attemptRun: autoRunAttemptRun,
  1635. });
  1636. }
  1637. // ============================================================
  1638. // Step Execution
  1639. // ============================================================
  1640. async function executeStep(step) {
  1641. console.log(LOG_PREFIX, `Executing step ${step}`);
  1642. throwIfStopped();
  1643. await setStepStatus(step, 'running');
  1644. await addLog(`步骤 ${step} 开始执行`);
  1645. await humanStepDelay();
  1646. const state = await getState();
  1647. // Set flow start time on first step
  1648. if (step === 1 && !state.flowStartTime) {
  1649. await setState({ flowStartTime: Date.now() });
  1650. }
  1651. try {
  1652. switch (step) {
  1653. case 1: await executeStep1(state); break;
  1654. case 2: await executeStep2(state); break;
  1655. case 3: await executeStep3(state); break;
  1656. case 4: await executeStep4(state); break;
  1657. case 5: await executeStep5(state); break;
  1658. case 6: await executeStep6(state); break;
  1659. case 7: await executeStep7(state); break;
  1660. case 8: await executeStep8(state); break;
  1661. case 9: await executeStep9(state); break;
  1662. default:
  1663. throw new Error(`未知步骤:${step}`);
  1664. }
  1665. } catch (err) {
  1666. if (isStopError(err)) {
  1667. await setStepStatus(step, 'stopped');
  1668. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  1669. throw err;
  1670. }
  1671. await setStepStatus(step, 'failed');
  1672. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  1673. throw err;
  1674. }
  1675. }
  1676. /**
  1677. * Execute a step and wait for it to complete before returning.
  1678. * @param {number} step
  1679. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  1680. */
  1681. async function executeStepAndWait(step, delayAfter = 2000) {
  1682. throwIfStopped();
  1683. if (AUTO_RUN_BACKGROUND_COMPLETED_STEPS.has(step)) {
  1684. await addLog(`自动运行:步骤 ${step} 由后台流程负责收尾,执行函数返回后将直接进入下一步。`, 'info');
  1685. await executeStep(step);
  1686. const latestState = await getState();
  1687. await addLog(`自动运行:步骤 ${step} 已执行返回,当前状态为 ${latestState.stepStatuses?.[step] || 'pending'},准备继续后续步骤。`, 'info');
  1688. } else {
  1689. await addLog(`自动运行:步骤 ${step} 已发起,正在等待完成信号(超时 ${AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS / 1000} 秒)。`, 'info');
  1690. const completionResultPromise = waitForStepComplete(step, AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS).then(
  1691. payload => ({ ok: true, payload }),
  1692. error => ({ ok: false, error }),
  1693. );
  1694. try {
  1695. await executeStep(step);
  1696. } catch (err) {
  1697. notifyStepError(step, getErrorMessage(err));
  1698. await completionResultPromise;
  1699. throw err;
  1700. }
  1701. const completionResult = await completionResultPromise;
  1702. if (!completionResult.ok) {
  1703. throw completionResult.error;
  1704. }
  1705. await addLog(`自动运行:步骤 ${step} 已收到完成信号,准备继续后续步骤。`, 'info');
  1706. }
  1707. // Extra delay for page transitions / DOM updates
  1708. if (delayAfter > 0) {
  1709. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  1710. }
  1711. }
  1712. async function fetchDuckEmail(options = {}) {
  1713. throwIfStopped();
  1714. const { generateNew = true } = options;
  1715. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  1716. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  1717. const result = await sendToContentScript('duck-mail', {
  1718. type: 'FETCH_DUCK_EMAIL',
  1719. source: 'background',
  1720. payload: { generateNew },
  1721. });
  1722. if (result?.error) {
  1723. throw new Error(result.error);
  1724. }
  1725. if (!result?.email) {
  1726. throw new Error('未返回 Duck 邮箱地址。');
  1727. }
  1728. await setEmailState(result.email);
  1729. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  1730. return result.email;
  1731. }
  1732. // ============================================================
  1733. // Auto Run Flow
  1734. // ============================================================
  1735. let autoRunActive = false;
  1736. let autoRunCurrentRun = 0;
  1737. let autoRunTotalRuns = 1;
  1738. let autoRunAttemptRun = 0;
  1739. const DUCK_EMAIL_MAX_ATTEMPTS = 5;
  1740. const VERIFICATION_POLL_MAX_ROUNDS = 5;
  1741. const AUTO_STEP_DELAYS = {
  1742. 1: 2000,
  1743. 2: 2000,
  1744. 3: 3000,
  1745. 4: 2000,
  1746. 5: 3000,
  1747. 6: 3000,
  1748. 7: 2000,
  1749. 8: 2000,
  1750. 9: 1000,
  1751. };
  1752. async function resumeAutoRunIfWaitingForEmail(options = {}) {
  1753. const { silent = false } = options;
  1754. const state = await getState();
  1755. if (!state.email || !isAutoRunPausedState(state)) {
  1756. return false;
  1757. }
  1758. if (resumeWaiter) {
  1759. if (!silent) {
  1760. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  1761. }
  1762. resumeWaiter.resolve();
  1763. resumeWaiter = null;
  1764. return true;
  1765. }
  1766. return false;
  1767. }
  1768. async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
  1769. const currentState = await getState();
  1770. if (currentState.email) {
  1771. return currentState.email;
  1772. }
  1773. let lastDuckError = null;
  1774. for (let duckAttempt = 1; duckAttempt <= DUCK_EMAIL_MAX_ATTEMPTS; duckAttempt++) {
  1775. try {
  1776. if (duckAttempt > 1) {
  1777. await addLog(`Duck 邮箱:正在进行第 ${duckAttempt}/${DUCK_EMAIL_MAX_ATTEMPTS} 次自动获取重试...`, 'warn');
  1778. }
  1779. const duckEmail = await fetchDuckEmail({ generateNew: true });
  1780. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:Duck 邮箱已就绪:${duckEmail}(第 ${attemptRuns} 次尝试,Duck 第 ${duckAttempt}/${DUCK_EMAIL_MAX_ATTEMPTS} 次获取)===`, 'ok');
  1781. return duckEmail;
  1782. } catch (err) {
  1783. lastDuckError = err;
  1784. await addLog(`Duck 邮箱自动获取失败(${duckAttempt}/${DUCK_EMAIL_MAX_ATTEMPTS}):${err.message}`, 'warn');
  1785. }
  1786. }
  1787. await addLog(`Duck 邮箱自动获取已连续失败 ${DUCK_EMAIL_MAX_ATTEMPTS} 次:${lastDuckError?.message || '未知错误'}`, 'error');
  1788. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先获取 Duck 邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  1789. await broadcastAutoRunStatus('waiting_email', {
  1790. currentRun: targetRun,
  1791. totalRuns,
  1792. attemptRun: attemptRuns,
  1793. });
  1794. await waitForResume();
  1795. const resumedState = await getState();
  1796. if (!resumedState.email) {
  1797. throw new Error('无法继续:当前没有邮箱地址。');
  1798. }
  1799. return resumedState.email;
  1800. }
  1801. async function runAutoSequenceFromStep(startStep, context = {}) {
  1802. const { targetRun, totalRuns, attemptRuns, continued = false } = context;
  1803. const maxStep9RestartAttempts = 5;
  1804. let step9RestartAttempts = 0;
  1805. if (continued) {
  1806. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续当前进度,从步骤 ${startStep} 开始(第 ${attemptRuns} 次尝试)===`, 'info');
  1807. } else {
  1808. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  1809. }
  1810. if (startStep <= 2) {
  1811. for (const step of [1, 2]) {
  1812. if (step < startStep) continue;
  1813. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1814. }
  1815. }
  1816. if (startStep <= 3) {
  1817. await ensureAutoEmailReady(targetRun, totalRuns, attemptRuns);
  1818. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  1819. await broadcastAutoRunStatus('running', {
  1820. currentRun: targetRun,
  1821. totalRuns,
  1822. attemptRun: attemptRuns,
  1823. });
  1824. await executeStepAndWait(3, AUTO_STEP_DELAYS[3]);
  1825. } else {
  1826. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续执行剩余流程(第 ${attemptRuns} 次尝试)===`, 'info');
  1827. }
  1828. const signupTabId = await getTabId('signup-page');
  1829. if (signupTabId) {
  1830. await chrome.tabs.update(signupTabId, { active: true });
  1831. }
  1832. let step = Math.max(startStep, 4);
  1833. while (step <= 9) {
  1834. try {
  1835. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1836. step += 1;
  1837. } catch (err) {
  1838. if (step === 9 && isStep9OAuthTimeoutError(err) && step9RestartAttempts < maxStep9RestartAttempts) {
  1839. step9RestartAttempts += 1;
  1840. await addLog(
  1841. `步骤 9:检测到 OAuth callback 超时,正在回到步骤 6 重新开始授权流程(${step9RestartAttempts}/${maxStep9RestartAttempts})...`,
  1842. 'warn'
  1843. );
  1844. await invalidateDownstreamAfterStepRestart(6, {
  1845. logLabel: `步骤 9 超时后准备回到步骤 6 重试(${step9RestartAttempts}/${maxStep9RestartAttempts})`,
  1846. });
  1847. step = 6;
  1848. continue;
  1849. }
  1850. throw err;
  1851. }
  1852. }
  1853. }
  1854. // Outer loop: keep retrying until the target number of successful runs is reached.
  1855. async function autoRunLoop(totalRuns, options = {}) {
  1856. if (autoRunActive) {
  1857. await addLog('自动运行已在进行中', 'warn');
  1858. return;
  1859. }
  1860. clearStopRequest();
  1861. autoRunActive = true;
  1862. autoRunTotalRuns = totalRuns;
  1863. autoRunCurrentRun = 0;
  1864. autoRunAttemptRun = 0;
  1865. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  1866. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  1867. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) ? options.resumeCurrentRun : 0;
  1868. const resumeSuccessfulRuns = Number.isInteger(options.resumeSuccessfulRuns) ? options.resumeSuccessfulRuns : 0;
  1869. const resumeAttemptRunsProcessed = Number.isInteger(options.resumeAttemptRunsProcessed) ? options.resumeAttemptRunsProcessed : 0;
  1870. let maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  1871. const forcedRetryCap = Math.max(totalRuns * 10, totalRuns + 20);
  1872. let successfulRuns = Math.max(0, resumeSuccessfulRuns);
  1873. let attemptRuns = Math.max(0, resumeAttemptRunsProcessed);
  1874. let forceFreshTabsNextRun = false;
  1875. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  1876. await setState({
  1877. autoRunSkipFailures,
  1878. ...getAutoRunStatusPayload('running', {
  1879. currentRun: resumeCurrentRun,
  1880. totalRuns,
  1881. attemptRun: resumeAttemptRunsProcessed,
  1882. }),
  1883. });
  1884. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  1885. attemptRuns += 1;
  1886. const targetRun = successfulRuns + 1;
  1887. autoRunCurrentRun = targetRun;
  1888. autoRunAttemptRun = attemptRuns;
  1889. let startStep = 1;
  1890. let useExistingProgress = false;
  1891. if (continueCurrentOnFirstAttempt) {
  1892. const currentState = await getState();
  1893. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  1894. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  1895. startStep = resumeStep;
  1896. useExistingProgress = true;
  1897. } else if (hasSavedProgress(currentState.stepStatuses)) {
  1898. await addLog('当前流程已全部处理,将按“重新开始”新开一轮自动运行。', 'info');
  1899. }
  1900. continueCurrentOnFirstAttempt = false;
  1901. }
  1902. if (!useExistingProgress) {
  1903. // Reset everything at the start of each fresh attempt (keep user settings).
  1904. const prevState = await getState();
  1905. const keepSettings = {
  1906. vpsUrl: prevState.vpsUrl,
  1907. vpsPassword: prevState.vpsPassword,
  1908. customPassword: prevState.customPassword,
  1909. autoRunSkipFailures: prevState.autoRunSkipFailures,
  1910. mailProvider: prevState.mailProvider,
  1911. inbucketHost: prevState.inbucketHost,
  1912. inbucketMailbox: prevState.inbucketMailbox,
  1913. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  1914. ...(forceFreshTabsNextRun ? { tabRegistry: {} } : {}),
  1915. };
  1916. await resetState();
  1917. await setState(keepSettings);
  1918. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => { });
  1919. await sleepWithStop(500);
  1920. } else {
  1921. await setState({
  1922. autoRunSkipFailures,
  1923. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  1924. });
  1925. }
  1926. if (forceFreshTabsNextRun) {
  1927. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  1928. forceFreshTabsNextRun = false;
  1929. }
  1930. try {
  1931. throwIfStopped();
  1932. await broadcastAutoRunStatus('running', {
  1933. currentRun: targetRun,
  1934. totalRuns,
  1935. attemptRun: attemptRuns,
  1936. });
  1937. await runAutoSequenceFromStep(startStep, {
  1938. targetRun,
  1939. totalRuns,
  1940. attemptRuns,
  1941. continued: useExistingProgress,
  1942. });
  1943. successfulRuns += 1;
  1944. autoRunCurrentRun = successfulRuns;
  1945. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  1946. continue;
  1947. } catch (err) {
  1948. if (isStopError(err)) {
  1949. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  1950. await broadcastAutoRunStatus('stopped', {
  1951. currentRun: targetRun,
  1952. totalRuns,
  1953. attemptRun: attemptRuns,
  1954. });
  1955. break;
  1956. }
  1957. if (isRestartCurrentAttemptError(err)) {
  1958. await addLog(`目标 ${targetRun}/${totalRuns} 轮检测到当前邮箱已存在,当前线程已放弃,将重新开始新一轮。`, 'warn');
  1959. cancelPendingCommands('当前线程因邮箱已存在而放弃。');
  1960. await broadcastStopToContentScripts();
  1961. await broadcastAutoRunStatus('retrying', {
  1962. currentRun: targetRun,
  1963. totalRuns,
  1964. attemptRun: attemptRuns,
  1965. });
  1966. forceFreshTabsNextRun = true;
  1967. maxAttempts = Math.max(maxAttempts, Math.min(forcedRetryCap, attemptRuns + 1));
  1968. continue;
  1969. }
  1970. if (!autoRunSkipFailures) {
  1971. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  1972. await broadcastAutoRunStatus('stopped', {
  1973. currentRun: targetRun,
  1974. totalRuns,
  1975. attemptRun: attemptRuns,
  1976. });
  1977. break;
  1978. }
  1979. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  1980. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  1981. cancelPendingCommands('当前尝试已放弃。');
  1982. await broadcastStopToContentScripts();
  1983. await broadcastAutoRunStatus('retrying', {
  1984. currentRun: targetRun,
  1985. totalRuns,
  1986. attemptRun: attemptRuns,
  1987. });
  1988. forceFreshTabsNextRun = true;
  1989. }
  1990. }
  1991. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  1992. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  1993. await broadcastAutoRunStatus('stopped', {
  1994. currentRun: successfulRuns,
  1995. totalRuns: autoRunTotalRuns,
  1996. attemptRun: attemptRuns,
  1997. });
  1998. } else if (stopRequested) {
  1999. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  2000. await broadcastAutoRunStatus('stopped', {
  2001. currentRun: successfulRuns,
  2002. totalRuns: autoRunTotalRuns,
  2003. attemptRun: attemptRuns,
  2004. });
  2005. } else if (successfulRuns >= autoRunTotalRuns) {
  2006. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  2007. await broadcastAutoRunStatus('complete', {
  2008. currentRun: successfulRuns,
  2009. totalRuns: autoRunTotalRuns,
  2010. attemptRun: attemptRuns,
  2011. });
  2012. } else {
  2013. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  2014. await broadcastAutoRunStatus('stopped', {
  2015. currentRun: successfulRuns,
  2016. totalRuns: autoRunTotalRuns,
  2017. attemptRun: attemptRuns,
  2018. });
  2019. }
  2020. autoRunActive = false;
  2021. autoRunAttemptRun = attemptRuns;
  2022. await setState(getAutoRunStatusPayload(stopRequested ? 'stopped' : (successfulRuns >= autoRunTotalRuns ? 'complete' : 'stopped'), {
  2023. currentRun: successfulRuns,
  2024. totalRuns: autoRunTotalRuns,
  2025. attemptRun: attemptRuns,
  2026. }));
  2027. clearStopRequest();
  2028. }
  2029. async function waitForResume() {
  2030. throwIfStopped();
  2031. const state = await getState();
  2032. if (state.email) {
  2033. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  2034. return;
  2035. }
  2036. return new Promise((resolve, reject) => {
  2037. resumeWaiter = { resolve, reject };
  2038. });
  2039. }
  2040. async function resumeAutoRun() {
  2041. throwIfStopped();
  2042. const state = await getState();
  2043. if (!state.email) {
  2044. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  2045. return false;
  2046. }
  2047. const resumedInMemory = await resumeAutoRunIfWaitingForEmail({ silent: true });
  2048. if (resumedInMemory) {
  2049. return true;
  2050. }
  2051. if (!isAutoRunPausedState(state)) {
  2052. return false;
  2053. }
  2054. if (autoRunActive) {
  2055. return false;
  2056. }
  2057. const totalRuns = state.autoRunTotalRuns || 1;
  2058. const currentRun = state.autoRunCurrentRun || 1;
  2059. const attemptRun = state.autoRunAttemptRun || 1;
  2060. const successfulRuns = Math.max(0, currentRun - 1);
  2061. await addLog('检测到自动流程暂停上下文已丢失,正在从当前进度恢复自动运行...', 'warn');
  2062. autoRunLoop(totalRuns, {
  2063. autoRunSkipFailures: Boolean(state.autoRunSkipFailures),
  2064. mode: 'continue',
  2065. resumeCurrentRun: currentRun,
  2066. resumeSuccessfulRuns: successfulRuns,
  2067. resumeAttemptRunsProcessed: Math.max(0, attemptRun - 1),
  2068. });
  2069. return true;
  2070. }
  2071. // ============================================================
  2072. // Step 1: Get OAuth Link (via vps-panel.js)
  2073. // ============================================================
  2074. async function executeStep1(state) {
  2075. if (!state.vpsUrl) {
  2076. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  2077. }
  2078. await addLog('步骤 1:正在打开 CPA 面板...');
  2079. const injectFiles = ['content/utils.js', 'content/vps-panel.js'];
  2080. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  2081. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  2082. const tabId = tab.id;
  2083. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  2084. await addLog('步骤 1:CPA 面板已打开,正在等待页面进入目标地址...');
  2085. const matchedTab = await waitForTabUrlFamily('vps-panel', tabId, state.vpsUrl, {
  2086. timeoutMs: 15000,
  2087. retryDelayMs: 400,
  2088. });
  2089. if (!matchedTab) {
  2090. await addLog('步骤 1:CPA 页面尚未完全进入目标地址,继续尝试连接内容脚本...', 'warn');
  2091. }
  2092. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  2093. inject: injectFiles,
  2094. timeoutMs: 45000,
  2095. retryDelayMs: 900,
  2096. logMessage: '步骤 1:CPA 面板仍在加载,正在重试连接内容脚本...',
  2097. });
  2098. const result = await sendToContentScriptResilient('vps-panel', {
  2099. type: 'EXECUTE_STEP',
  2100. step: 1,
  2101. source: 'background',
  2102. payload: { vpsPassword: state.vpsPassword },
  2103. }, {
  2104. timeoutMs: 30000,
  2105. retryDelayMs: 700,
  2106. logMessage: '步骤 1:CPA 面板通信未就绪,正在等待页面恢复...',
  2107. });
  2108. if (result?.error) {
  2109. throw new Error(result.error);
  2110. }
  2111. }
  2112. // ============================================================
  2113. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  2114. // ============================================================
  2115. async function executeStep2(state) {
  2116. if (!state.oauthUrl) {
  2117. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  2118. }
  2119. await addLog('步骤 2:正在打开认证链接...');
  2120. await reuseOrCreateTab('signup-page', state.oauthUrl);
  2121. await sendToContentScript('signup-page', {
  2122. type: 'EXECUTE_STEP',
  2123. step: 2,
  2124. source: 'background',
  2125. payload: {},
  2126. });
  2127. }
  2128. // ============================================================
  2129. // Step 3: Fill Email & Password (via signup-page.js)
  2130. // ============================================================
  2131. async function executeStep3(state) {
  2132. if (!state.email) {
  2133. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  2134. }
  2135. const password = state.customPassword || generatePassword();
  2136. await setPasswordState(password);
  2137. // Save account record
  2138. const accounts = state.accounts || [];
  2139. accounts.push({ email: state.email, password, createdAt: new Date().toISOString() });
  2140. await setState({ accounts });
  2141. await addLog(
  2142. `步骤 3:正在填写邮箱 ${state.email},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  2143. );
  2144. await sendToContentScript('signup-page', {
  2145. type: 'EXECUTE_STEP',
  2146. step: 3,
  2147. source: 'background',
  2148. payload: { email: state.email, password },
  2149. });
  2150. }
  2151. // ============================================================
  2152. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  2153. // ============================================================
  2154. function getMailConfig(state) {
  2155. const provider = state.mailProvider || 'qq';
  2156. if (provider === '163') {
  2157. 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 邮箱' };
  2158. }
  2159. if (provider === '163-vip') {
  2160. 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 邮箱' };
  2161. }
  2162. if (provider === 'inbucket') {
  2163. const host = normalizeInbucketOrigin(state.inbucketHost);
  2164. const mailbox = (state.inbucketMailbox || '').trim();
  2165. if (!host) {
  2166. return { error: 'Inbucket 主机地址为空或无效。' };
  2167. }
  2168. if (!mailbox) {
  2169. return { error: 'Inbucket 邮箱名称为空。' };
  2170. }
  2171. return {
  2172. source: 'inbucket-mail',
  2173. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  2174. label: `Inbucket 邮箱(${mailbox})`,
  2175. navigateOnReuse: true,
  2176. inject: ['content/utils.js', 'content/inbucket-mail.js'],
  2177. injectSource: 'inbucket-mail',
  2178. };
  2179. }
  2180. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  2181. }
  2182. function normalizeInbucketOrigin(rawValue) {
  2183. const value = (rawValue || '').trim();
  2184. if (!value) return '';
  2185. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  2186. try {
  2187. const parsed = new URL(candidate);
  2188. return parsed.origin;
  2189. } catch {
  2190. return '';
  2191. }
  2192. }
  2193. function getVerificationCodeStateKey(step) {
  2194. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  2195. }
  2196. function getVerificationCodeLabel(step) {
  2197. return step === 4 ? '注册' : '登录';
  2198. }
  2199. function getVerificationPollPayload(step, state, overrides = {}) {
  2200. if (step === 4) {
  2201. return {
  2202. filterAfterTimestamp: state.flowStartTime || 0,
  2203. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  2204. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  2205. targetEmail: state.email,
  2206. maxAttempts: 5,
  2207. intervalMs: 3000,
  2208. ...overrides,
  2209. };
  2210. }
  2211. return {
  2212. filterAfterTimestamp: state.lastEmailTimestamp || state.flowStartTime || 0,
  2213. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  2214. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  2215. targetEmail: state.email,
  2216. maxAttempts: 5,
  2217. intervalMs: 3000,
  2218. ...overrides,
  2219. };
  2220. }
  2221. async function requestVerificationCodeResend(step) {
  2222. const signupTabId = await getTabId('signup-page');
  2223. if (!signupTabId) {
  2224. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  2225. }
  2226. await chrome.tabs.update(signupTabId, { active: true });
  2227. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  2228. const result = await sendToContentScript('signup-page', {
  2229. type: 'RESEND_VERIFICATION_CODE',
  2230. step,
  2231. source: 'background',
  2232. payload: {},
  2233. });
  2234. if (result && result.error) {
  2235. throw new Error(result.error);
  2236. }
  2237. if (step === 7) {
  2238. const restartError = getStep7RestartFromStep6Error(result);
  2239. if (restartError) {
  2240. throw restartError;
  2241. }
  2242. }
  2243. return Date.now();
  2244. }
  2245. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  2246. const stateKey = getVerificationCodeStateKey(step);
  2247. const rejectedCodes = new Set();
  2248. if (state[stateKey]) {
  2249. rejectedCodes.add(state[stateKey]);
  2250. }
  2251. for (const code of (pollOverrides.excludeCodes || [])) {
  2252. if (code) rejectedCodes.add(code);
  2253. }
  2254. let lastError = null;
  2255. const filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  2256. const maxRounds = pollOverrides.maxRounds || VERIFICATION_POLL_MAX_ROUNDS;
  2257. for (let round = 1; round <= maxRounds; round++) {
  2258. if (round > 1) {
  2259. await requestVerificationCodeResend(step);
  2260. }
  2261. const payload = getVerificationPollPayload(step, state, {
  2262. ...pollOverrides,
  2263. filterAfterTimestamp,
  2264. excludeCodes: [...rejectedCodes],
  2265. });
  2266. try {
  2267. const result = await sendToMailContentScriptResilient(
  2268. mail,
  2269. {
  2270. type: 'POLL_EMAIL',
  2271. step,
  2272. source: 'background',
  2273. payload,
  2274. },
  2275. {
  2276. timeoutMs: 45000,
  2277. maxRecoveryAttempts: 2,
  2278. }
  2279. );
  2280. if (result && result.error) {
  2281. throw new Error(result.error);
  2282. }
  2283. if (!result || !result.code) {
  2284. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  2285. }
  2286. if (rejectedCodes.has(result.code)) {
  2287. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  2288. }
  2289. return result;
  2290. } catch (err) {
  2291. lastError = err;
  2292. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  2293. if (round < maxRounds) {
  2294. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  2295. }
  2296. }
  2297. }
  2298. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  2299. }
  2300. async function submitVerificationCode(step, code) {
  2301. const signupTabId = await getTabId('signup-page');
  2302. if (!signupTabId) {
  2303. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  2304. }
  2305. await chrome.tabs.update(signupTabId, { active: true });
  2306. const result = await sendToContentScript('signup-page', {
  2307. type: 'FILL_CODE',
  2308. step,
  2309. source: 'background',
  2310. payload: { code },
  2311. });
  2312. if (result && result.error) {
  2313. throw new Error(result.error);
  2314. }
  2315. if (step === 7) {
  2316. const restartError = getStep7RestartFromStep6Error(result);
  2317. if (restartError) {
  2318. throw restartError;
  2319. }
  2320. }
  2321. return result || {};
  2322. }
  2323. async function resolveVerificationStep(step, state, mail, options = {}) {
  2324. const stateKey = getVerificationCodeStateKey(step);
  2325. const rejectedCodes = new Set();
  2326. if (state[stateKey]) {
  2327. rejectedCodes.add(state[stateKey]);
  2328. }
  2329. const nextFilterAfterTimestamp = options.filterAfterTimestamp ?? null;
  2330. const requestFreshCodeFirst = Boolean(options.requestFreshCodeFirst);
  2331. const maxSubmitAttempts = 3;
  2332. if (requestFreshCodeFirst) {
  2333. try {
  2334. await requestVerificationCodeResend(step);
  2335. await addLog(`步骤 ${step}:已先请求一封新的${getVerificationCodeLabel(step)}验证码,再开始轮询邮箱。`, 'warn');
  2336. } catch (err) {
  2337. if (step === 7 && isStep7RestartFromStep6Error(err)) {
  2338. throw err;
  2339. }
  2340. await addLog(`步骤 ${step}:首次重新获取验证码失败:${err.message},将继续使用当前时间窗口轮询。`, 'warn');
  2341. }
  2342. }
  2343. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  2344. const result = await pollFreshVerificationCode(step, state, mail, {
  2345. excludeCodes: [...rejectedCodes],
  2346. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  2347. });
  2348. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  2349. const submitResult = await submitVerificationCode(step, result.code);
  2350. if (submitResult.invalidCode) {
  2351. rejectedCodes.add(result.code);
  2352. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  2353. if (attempt >= maxSubmitAttempts) {
  2354. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  2355. }
  2356. await requestVerificationCodeResend(step);
  2357. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  2358. continue;
  2359. }
  2360. await setState({
  2361. lastEmailTimestamp: result.emailTimestamp,
  2362. [stateKey]: result.code,
  2363. });
  2364. await completeStepFromBackground(step, {
  2365. emailTimestamp: result.emailTimestamp,
  2366. code: result.code,
  2367. });
  2368. return;
  2369. }
  2370. }
  2371. async function executeStep4(state) {
  2372. const mail = getMailConfig(state);
  2373. if (mail.error) throw new Error(mail.error);
  2374. const stepStartedAt = Date.now();
  2375. const signupTabId = await getTabId('signup-page');
  2376. if (!signupTabId) {
  2377. throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
  2378. }
  2379. await chrome.tabs.update(signupTabId, { active: true });
  2380. await addLog('步骤 4:正在确认注册验证码页面是否就绪,必要时自动恢复密码页超时报错...');
  2381. const prepareResult = await sendToContentScriptResilient(
  2382. 'signup-page',
  2383. {
  2384. type: 'PREPARE_SIGNUP_VERIFICATION',
  2385. step: 4,
  2386. source: 'background',
  2387. payload: { password: state.password || state.customPassword || '' },
  2388. },
  2389. {
  2390. timeoutMs: 30000,
  2391. retryDelayMs: 700,
  2392. logMessage: '步骤 4:认证页正在切换,等待页面重新就绪后继续检测...',
  2393. }
  2394. );
  2395. if (prepareResult && prepareResult.error) {
  2396. throw new Error(prepareResult.error);
  2397. }
  2398. if (prepareResult?.alreadyVerified) {
  2399. await completeStepFromBackground(4, {});
  2400. return;
  2401. }
  2402. await addLog(`步骤 4:正在打开${mail.label}...`);
  2403. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  2404. const alive = await isTabAlive(mail.source);
  2405. if (alive) {
  2406. if (mail.navigateOnReuse) {
  2407. await reuseOrCreateTab(mail.source, mail.url, {
  2408. inject: mail.inject,
  2409. injectSource: mail.injectSource,
  2410. });
  2411. } else {
  2412. const tabId = await getTabId(mail.source);
  2413. await chrome.tabs.update(tabId, { active: true });
  2414. }
  2415. } else {
  2416. await reuseOrCreateTab(mail.source, mail.url, {
  2417. inject: mail.inject,
  2418. injectSource: mail.injectSource,
  2419. });
  2420. }
  2421. await resolveVerificationStep(4, state, mail, {
  2422. filterAfterTimestamp: stepStartedAt,
  2423. requestFreshCodeFirst: true,
  2424. });
  2425. return;
  2426. }
  2427. // ============================================================
  2428. // Step 5: Fill Name & Birthday (via signup-page.js)
  2429. // ============================================================
  2430. async function executeStep5(state) {
  2431. const { firstName, lastName } = generateRandomName();
  2432. const { year, month, day } = generateRandomBirthday();
  2433. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  2434. await sendToContentScript('signup-page', {
  2435. type: 'EXECUTE_STEP',
  2436. step: 5,
  2437. source: 'background',
  2438. payload: { firstName, lastName, year, month, day },
  2439. });
  2440. }
  2441. // ============================================================
  2442. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  2443. // ============================================================
  2444. async function refreshOAuthUrlBeforeStep6(state) {
  2445. if (!state.vpsUrl) {
  2446. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  2447. }
  2448. await addLog('步骤 6:正在刷新登录用的 CPA OAuth 链接...');
  2449. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] preparing fresh OAuth via step 1');
  2450. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  2451. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] executing step 1 for fresh OAuth');
  2452. await executeStep1(state);
  2453. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 execute returned, waiting for completion signal');
  2454. await waitForFreshOAuth;
  2455. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 completion signal received');
  2456. const latestState = await getState();
  2457. if (!latestState.oauthUrl) {
  2458. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  2459. }
  2460. return latestState.oauthUrl;
  2461. }
  2462. async function executeStep6(state) {
  2463. if (!state.email) {
  2464. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  2465. }
  2466. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  2467. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  2468. // Reuse the signup-page tab — navigate it to the OAuth URL
  2469. await reuseOrCreateTab('signup-page', oauthUrl);
  2470. // signup-page.js will inject (same auth.openai.com domain) and handle login
  2471. await sendToContentScript('signup-page', {
  2472. type: 'EXECUTE_STEP',
  2473. step: 6,
  2474. source: 'background',
  2475. payload: { email: state.email, password: state.password },
  2476. });
  2477. }
  2478. // ============================================================
  2479. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  2480. // ============================================================
  2481. async function runStep7Attempt(state) {
  2482. const mail = getMailConfig(state);
  2483. if (mail.error) throw new Error(mail.error);
  2484. const stepStartedAt = Date.now();
  2485. const authTabId = await getTabId('signup-page');
  2486. if (authTabId) {
  2487. await chrome.tabs.update(authTabId, { active: true });
  2488. } else {
  2489. if (!state.oauthUrl) {
  2490. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  2491. }
  2492. await reuseOrCreateTab('signup-page', state.oauthUrl);
  2493. }
  2494. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  2495. const prepareResult = await sendToContentScript('signup-page', {
  2496. type: 'PREPARE_LOGIN_CODE',
  2497. step: 7,
  2498. source: 'background',
  2499. payload: {},
  2500. });
  2501. if (prepareResult && prepareResult.error) {
  2502. throw new Error(prepareResult.error);
  2503. }
  2504. const restartError = getStep7RestartFromStep6Error(prepareResult);
  2505. if (restartError) {
  2506. throw restartError;
  2507. }
  2508. await addLog(`步骤 7:正在打开${mail.label}...`);
  2509. const alive = await isTabAlive(mail.source);
  2510. if (alive) {
  2511. if (mail.navigateOnReuse) {
  2512. await reuseOrCreateTab(mail.source, mail.url, {
  2513. inject: mail.inject,
  2514. injectSource: mail.injectSource,
  2515. });
  2516. } else {
  2517. const tabId = await getTabId(mail.source);
  2518. await chrome.tabs.update(tabId, { active: true });
  2519. }
  2520. } else {
  2521. await reuseOrCreateTab(mail.source, mail.url, {
  2522. inject: mail.inject,
  2523. injectSource: mail.injectSource,
  2524. });
  2525. }
  2526. await resolveVerificationStep(7, state, mail, {
  2527. filterAfterTimestamp: stepStartedAt,
  2528. requestFreshCodeFirst: true,
  2529. });
  2530. }
  2531. async function rerunStep6ForStep7Recovery() {
  2532. const currentState = await getState();
  2533. const waitForStep6 = waitForStepComplete(6, 120000);
  2534. await addLog('步骤 7:正在回到步骤 6,重新发起登录验证码流程...', 'warn');
  2535. await executeStep6(currentState);
  2536. await waitForStep6;
  2537. await sleepWithStop(3000);
  2538. }
  2539. async function executeStep7(state) {
  2540. let lastError = null;
  2541. for (let round = 1; round <= STEP7_RESTART_MAX_ROUNDS; round++) {
  2542. const currentState = round === 1 ? state : await getState();
  2543. try {
  2544. if (round > 1) {
  2545. await addLog(`步骤 7:正在进行第 ${round}/${STEP7_RESTART_MAX_ROUNDS} 轮登录验证码恢复尝试。`, 'warn');
  2546. }
  2547. await runStep7Attempt(currentState);
  2548. return;
  2549. } catch (err) {
  2550. lastError = err;
  2551. if (!isStep7RecoverableError(err)) {
  2552. throw err;
  2553. }
  2554. if (round >= STEP7_RESTART_MAX_ROUNDS) {
  2555. break;
  2556. }
  2557. await addLog(
  2558. isStep7RestartFromStep6Error(err)
  2559. ? `步骤 7:检测到登录页超时报错,准备从步骤 6 重新开始(${round + 1}/${STEP7_RESTART_MAX_ROUNDS})...`
  2560. : `步骤 7:检测到邮箱轮询类失败,准备从步骤 6 重新开始(${round + 1}/${STEP7_RESTART_MAX_ROUNDS})...`,
  2561. 'warn'
  2562. );
  2563. await rerunStep6ForStep7Recovery();
  2564. }
  2565. }
  2566. if (lastError && isStep7RecoverableError(lastError)) {
  2567. throw new Error(`步骤 7:登录验证码流程在 ${STEP7_RESTART_MAX_ROUNDS} 轮恢复后仍未成功。最后一次原因:${lastError.message}`);
  2568. }
  2569. throw lastError || new Error(`步骤 7:登录验证码流程在 ${STEP7_RESTART_MAX_ROUNDS} 轮后仍未成功。`);
  2570. }
  2571. // ============================================================
  2572. // Step 8: 完成 OAuth(自动点击 + localhost 回调监听)
  2573. // ============================================================
  2574. let webNavListener = null;
  2575. let webNavCommittedListener = null;
  2576. let step8TabUpdatedListener = null;
  2577. let step8PendingReject = null;
  2578. const STEP8_CLICK_EFFECT_TIMEOUT_MS = 10000;
  2579. const STEP8_CLICK_RETRY_DELAY_MS = 500;
  2580. const STEP8_READY_WAIT_TIMEOUT_MS = 30000;
  2581. const STEP8_MAX_ROUNDS = 5;
  2582. const STEP8_SIGNUP_PAGE_INJECT_FILES = ['content/utils.js', 'content/signup-page.js'];
  2583. const STEP8_STRATEGIES = [
  2584. { mode: 'content', strategy: 'requestSubmit', label: 'form.requestSubmit' },
  2585. { mode: 'debugger', label: 'debugger click' },
  2586. { mode: 'content', strategy: 'nativeClick', label: 'element.click' },
  2587. { mode: 'content', strategy: 'dispatchClick', label: 'dispatch click' },
  2588. { mode: 'debugger', label: 'debugger click retry' },
  2589. ];
  2590. function cleanupStep8NavigationListeners() {
  2591. if (webNavListener) {
  2592. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  2593. webNavListener = null;
  2594. }
  2595. if (webNavCommittedListener) {
  2596. chrome.webNavigation.onCommitted.removeListener(webNavCommittedListener);
  2597. webNavCommittedListener = null;
  2598. }
  2599. if (step8TabUpdatedListener) {
  2600. chrome.tabs.onUpdated.removeListener(step8TabUpdatedListener);
  2601. step8TabUpdatedListener = null;
  2602. }
  2603. }
  2604. function rejectPendingStep8(error) {
  2605. if (!step8PendingReject) return;
  2606. const reject = step8PendingReject;
  2607. step8PendingReject = null;
  2608. reject(error);
  2609. }
  2610. function throwIfStep8SettledOrStopped(isSettled = false) {
  2611. if (isSettled || stopRequested) {
  2612. throw new Error(STOP_ERROR_MESSAGE);
  2613. }
  2614. }
  2615. async function ensureStep8SignupPageReady(tabId, options = {}) {
  2616. await ensureContentScriptReadyOnTab('signup-page', tabId, {
  2617. inject: STEP8_SIGNUP_PAGE_INJECT_FILES,
  2618. injectSource: 'signup-page',
  2619. timeoutMs: options.timeoutMs ?? 15000,
  2620. retryDelayMs: options.retryDelayMs ?? 600,
  2621. logMessage: options.logMessage || '',
  2622. });
  2623. }
  2624. async function getStep8PageState(tabId, responseTimeoutMs = 1500) {
  2625. try {
  2626. const result = await sendTabMessageWithTimeout(tabId, 'signup-page', {
  2627. type: 'STEP8_GET_STATE',
  2628. source: 'background',
  2629. payload: {},
  2630. }, responseTimeoutMs);
  2631. if (result?.error) {
  2632. throw new Error(result.error);
  2633. }
  2634. return result;
  2635. } catch (err) {
  2636. if (isRetryableContentScriptTransportError(err)) {
  2637. return null;
  2638. }
  2639. throw err;
  2640. }
  2641. }
  2642. async function waitForStep8Ready(tabId, timeoutMs = STEP8_READY_WAIT_TIMEOUT_MS) {
  2643. const start = Date.now();
  2644. let recovered = false;
  2645. while (Date.now() - start < timeoutMs) {
  2646. throwIfStopped();
  2647. const pageState = await getStep8PageState(tabId);
  2648. if (pageState?.addPhonePage) {
  2649. throw new Error('步骤 8:认证页进入了手机号页面,当前不是 OAuth 同意页,无法继续自动授权。');
  2650. }
  2651. if (pageState?.consentReady) {
  2652. return pageState;
  2653. }
  2654. if (pageState === null && !recovered) {
  2655. recovered = true;
  2656. await ensureStep8SignupPageReady(tabId, {
  2657. timeoutMs: Math.min(10000, timeoutMs),
  2658. logMessage: '步骤 8:认证页内容脚本已失联,正在等待页面重新就绪...',
  2659. });
  2660. continue;
  2661. }
  2662. recovered = false;
  2663. await sleepWithStop(250);
  2664. }
  2665. throw new Error('步骤 8:长时间未进入 OAuth 同意页,无法定位“继续”按钮。');
  2666. }
  2667. async function prepareStep8DebuggerClick(tabId) {
  2668. await ensureStep8SignupPageReady(tabId, {
  2669. timeoutMs: 15000,
  2670. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续定位按钮...',
  2671. });
  2672. const result = await sendToContentScriptResilient('signup-page', {
  2673. type: 'STEP8_FIND_AND_CLICK',
  2674. source: 'background',
  2675. payload: {},
  2676. }, {
  2677. timeoutMs: 15000,
  2678. retryDelayMs: 600,
  2679. logMessage: '步骤 8:认证页正在切换,等待 OAuth 同意页按钮重新就绪...',
  2680. });
  2681. if (result?.error) {
  2682. throw new Error(result.error);
  2683. }
  2684. return result;
  2685. }
  2686. async function triggerStep8ContentStrategy(tabId, strategy) {
  2687. await ensureStep8SignupPageReady(tabId, {
  2688. timeoutMs: 15000,
  2689. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续点击“继续”按钮...',
  2690. });
  2691. const result = await sendToContentScriptResilient('signup-page', {
  2692. type: 'STEP8_TRIGGER_CONTINUE',
  2693. source: 'background',
  2694. payload: {
  2695. strategy,
  2696. findTimeoutMs: 4000,
  2697. enabledTimeoutMs: 3000,
  2698. },
  2699. }, {
  2700. timeoutMs: 15000,
  2701. retryDelayMs: 600,
  2702. logMessage: '步骤 8:认证页正在切换,等待“继续”按钮重新就绪...',
  2703. });
  2704. if (result?.error) {
  2705. throw new Error(result.error);
  2706. }
  2707. return result;
  2708. }
  2709. async function reloadStep8ConsentPage(tabId, timeoutMs = 30000) {
  2710. if (!Number.isInteger(tabId)) {
  2711. throw new Error('步骤 8:缺少有效的认证页标签页,无法刷新后重试。');
  2712. }
  2713. await chrome.tabs.update(tabId, { active: true }).catch(() => { });
  2714. await new Promise((resolve, reject) => {
  2715. let settled = false;
  2716. const timer = setTimeout(() => {
  2717. if (settled) return;
  2718. settled = true;
  2719. chrome.tabs.onUpdated.removeListener(listener);
  2720. reject(new Error('步骤 8:刷新认证页后等待页面完成加载超时。'));
  2721. }, timeoutMs);
  2722. const listener = (updatedTabId, changeInfo) => {
  2723. if (updatedTabId !== tabId) return;
  2724. if (changeInfo.status !== 'complete') return;
  2725. if (settled) return;
  2726. settled = true;
  2727. clearTimeout(timer);
  2728. chrome.tabs.onUpdated.removeListener(listener);
  2729. resolve();
  2730. };
  2731. chrome.tabs.onUpdated.addListener(listener);
  2732. chrome.tabs.reload(tabId, { bypassCache: false }).catch((err) => {
  2733. if (settled) return;
  2734. settled = true;
  2735. clearTimeout(timer);
  2736. chrome.tabs.onUpdated.removeListener(listener);
  2737. reject(err);
  2738. });
  2739. });
  2740. await ensureStep8SignupPageReady(tabId, {
  2741. timeoutMs: Math.min(15000, timeoutMs),
  2742. logMessage: '步骤 8:认证页刷新后内容脚本尚未就绪,正在等待页面恢复...',
  2743. });
  2744. }
  2745. async function waitForStep8ClickEffect(tabId, baselineUrl, timeoutMs = STEP8_CLICK_EFFECT_TIMEOUT_MS) {
  2746. const start = Date.now();
  2747. let recovered = false;
  2748. while (Date.now() - start < timeoutMs) {
  2749. throwIfStopped();
  2750. const tab = await chrome.tabs.get(tabId).catch(() => null);
  2751. if (!tab) {
  2752. throw new Error('步骤 8:认证页面标签页已关闭,无法继续自动授权。');
  2753. }
  2754. if (baselineUrl && typeof tab.url === 'string' && tab.url !== baselineUrl) {
  2755. return { progressed: true, reason: 'url_changed', url: tab.url };
  2756. }
  2757. const pageState = await getStep8PageState(tabId);
  2758. if (pageState?.addPhonePage) {
  2759. throw new Error('步骤 8:点击“继续”后页面跳到了手机号页面,当前流程无法继续自动授权。');
  2760. }
  2761. if (pageState === null) {
  2762. if (!recovered) {
  2763. recovered = true;
  2764. await ensureStep8SignupPageReady(tabId, {
  2765. timeoutMs: Math.max(3000, Math.min(8000, timeoutMs)),
  2766. logMessage: '步骤 8:点击后认证页正在重载,正在等待内容脚本重新就绪...',
  2767. }).catch(() => null);
  2768. continue;
  2769. }
  2770. await sleepWithStop(200);
  2771. continue;
  2772. }
  2773. recovered = false;
  2774. await sleepWithStop(200);
  2775. }
  2776. return { progressed: false, reason: 'no_effect' };
  2777. }
  2778. function getStep8EffectLabel(effect) {
  2779. switch (effect?.reason) {
  2780. case 'url_changed':
  2781. return `URL 已变化:${effect.url}`;
  2782. case 'page_reloading':
  2783. return '页面正在跳转或重载';
  2784. case 'left_consent_page':
  2785. return `页面已离开 OAuth 同意页:${effect.url || 'unknown'}`;
  2786. default:
  2787. return '页面仍停留在 OAuth 同意页';
  2788. }
  2789. }
  2790. async function executeStep8(state) {
  2791. if (!state.oauthUrl) {
  2792. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  2793. }
  2794. await addLog('步骤 8:正在监听 localhost 回调地址...');
  2795. return new Promise((resolve, reject) => {
  2796. let resolved = false;
  2797. let signupTabId = null;
  2798. const cleanupListener = () => {
  2799. cleanupStep8NavigationListeners();
  2800. step8PendingReject = null;
  2801. };
  2802. const rejectStep8 = (error) => {
  2803. if (resolved) return;
  2804. resolved = true;
  2805. clearTimeout(timeout);
  2806. cleanupListener();
  2807. reject(error);
  2808. };
  2809. const finalizeStep8Callback = (callbackUrl) => {
  2810. if (resolved || !callbackUrl) return;
  2811. resolved = true;
  2812. cleanupListener();
  2813. clearTimeout(timeout);
  2814. addLog(`步骤 8:已捕获 localhost 地址:${callbackUrl}`, 'ok').then(() => {
  2815. return completeStepFromBackground(8, { localhostUrl: callbackUrl });
  2816. }).then(() => {
  2817. resolve();
  2818. }).catch((err) => {
  2819. reject(err);
  2820. });
  2821. };
  2822. const timeout = setTimeout(() => {
  2823. rejectStep8(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  2824. }, 120000);
  2825. step8PendingReject = (error) => {
  2826. rejectStep8(error);
  2827. };
  2828. webNavListener = (details) => {
  2829. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  2830. finalizeStep8Callback(callbackUrl);
  2831. };
  2832. webNavCommittedListener = (details) => {
  2833. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  2834. finalizeStep8Callback(callbackUrl);
  2835. };
  2836. step8TabUpdatedListener = (tabId, changeInfo, tab) => {
  2837. const callbackUrl = getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId);
  2838. finalizeStep8Callback(callbackUrl);
  2839. };
  2840. (async () => {
  2841. try {
  2842. throwIfStep8SettledOrStopped(resolved);
  2843. signupTabId = await getTabId('signup-page');
  2844. throwIfStep8SettledOrStopped(resolved);
  2845. if (signupTabId && await isTabAlive('signup-page')) {
  2846. await chrome.tabs.update(signupTabId, { active: true });
  2847. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  2848. } else {
  2849. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  2850. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  2851. }
  2852. throwIfStep8SettledOrStopped(resolved);
  2853. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  2854. chrome.webNavigation.onCommitted.addListener(webNavCommittedListener);
  2855. chrome.tabs.onUpdated.addListener(step8TabUpdatedListener);
  2856. await ensureStep8SignupPageReady(signupTabId, {
  2857. timeoutMs: 15000,
  2858. logMessage: '步骤 8:认证页内容脚本尚未就绪,正在等待页面恢复...',
  2859. });
  2860. for (let round = 1; round <= STEP8_MAX_ROUNDS && !resolved; round++) {
  2861. throwIfStep8SettledOrStopped(resolved);
  2862. const pageState = await waitForStep8Ready(signupTabId);
  2863. if (!pageState?.consentReady) {
  2864. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  2865. continue;
  2866. }
  2867. const strategy = STEP8_STRATEGIES[Math.min(round - 1, STEP8_STRATEGIES.length - 1)];
  2868. await addLog(`步骤 8:第 ${round}/${STEP8_MAX_ROUNDS} 轮尝试点击“继续”(${strategy.label})...`);
  2869. if (strategy.mode === 'debugger') {
  2870. const clickTarget = await prepareStep8DebuggerClick(signupTabId);
  2871. throwIfStep8SettledOrStopped(resolved);
  2872. await clickWithDebugger(signupTabId, clickTarget?.rect);
  2873. } else {
  2874. await triggerStep8ContentStrategy(signupTabId, strategy.strategy);
  2875. }
  2876. if (resolved) {
  2877. return;
  2878. }
  2879. const effect = await waitForStep8ClickEffect(signupTabId, pageState.url);
  2880. if (resolved) {
  2881. return;
  2882. }
  2883. if (effect.progressed) {
  2884. await addLog(`步骤 8:检测到本次点击已生效,${getStep8EffectLabel(effect)},继续等待 localhost 回调...`, 'info');
  2885. break;
  2886. }
  2887. if (round >= STEP8_MAX_ROUNDS) {
  2888. throw new Error(`步骤 8:连续 ${STEP8_MAX_ROUNDS} 轮点击“继续”后页面仍无反应。`);
  2889. }
  2890. await addLog(`步骤 8:${strategy.label} 本轮点击后页面无反应,正在刷新认证页后重试(下一轮 ${round + 1}/${STEP8_MAX_ROUNDS})...`, 'warn');
  2891. await reloadStep8ConsentPage(signupTabId);
  2892. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  2893. }
  2894. } catch (err) {
  2895. rejectStep8(err);
  2896. }
  2897. })();
  2898. });
  2899. }
  2900. // ============================================================
  2901. // Step 9: CPA 回调验证(通过 vps-panel.js)
  2902. // ============================================================
  2903. async function executeStep9(state) {
  2904. if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
  2905. throw new Error('步骤 8 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 8。');
  2906. }
  2907. if (!state.localhostUrl) {
  2908. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  2909. }
  2910. if (!state.vpsUrl) {
  2911. throw new Error('尚未填写 CPA 地址,请先在侧边栏输入。');
  2912. }
  2913. if (shouldBypassStep9ForLocalCpa(state)) {
  2914. await addLog('步骤 9:检测到本地 CPA,步骤 8 完成后已自动添加,无需重复提交回调地址。', 'info');
  2915. await completeStepFromBackground(9, {
  2916. localhostUrl: state.localhostUrl,
  2917. verifiedStatus: 'local-auto',
  2918. });
  2919. return;
  2920. }
  2921. await addLog('步骤 9:正在打开 CPA 面板...');
  2922. const injectFiles = ['content/utils.js', 'content/vps-panel.js'];
  2923. let tabId = await getTabId('vps-panel');
  2924. const alive = tabId && await isTabAlive('vps-panel');
  2925. if (!alive) {
  2926. tabId = await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  2927. inject: injectFiles,
  2928. reloadIfSameUrl: true,
  2929. });
  2930. } else {
  2931. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  2932. await chrome.tabs.update(tabId, { active: true });
  2933. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  2934. }
  2935. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  2936. inject: injectFiles,
  2937. });
  2938. await addLog('步骤 9:正在填写回调地址...');
  2939. const result = await sendToContentScriptResilient('vps-panel', {
  2940. type: 'EXECUTE_STEP',
  2941. step: 9,
  2942. source: 'background',
  2943. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  2944. }, {
  2945. timeoutMs: 30000,
  2946. retryDelayMs: 700,
  2947. logMessage: '步骤 9:CPA 面板通信未就绪,正在等待页面恢复...',
  2948. });
  2949. if (result?.error) {
  2950. throw new Error(result.error);
  2951. }
  2952. }
  2953. // ============================================================
  2954. // Open Side Panel on extension icon click
  2955. // ============================================================
  2956. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
  2957. chrome.alarms.onAlarm.addListener((alarm) => {
  2958. if (alarm.name !== AUTO_RUN_ALARM_NAME) {
  2959. return;
  2960. }
  2961. launchScheduledAutoRun('alarm').catch((err) => {
  2962. console.error(LOG_PREFIX, 'Failed to launch scheduled auto run from alarm:', err);
  2963. });
  2964. });
  2965. chrome.runtime.onStartup.addListener(() => {
  2966. restoreScheduledAutoRunIfNeeded().catch((err) => {
  2967. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on startup:', err);
  2968. });
  2969. });
  2970. chrome.runtime.onInstalled.addListener(() => {
  2971. restoreScheduledAutoRunIfNeeded().catch((err) => {
  2972. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on install/update:', err);
  2973. });
  2974. });
  2975. restoreScheduledAutoRunIfNeeded().catch((err) => {
  2976. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run:', err);
  2977. });