background.js 112 KB

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