background.js 110 KB

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