background.js 145 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368
  1. // background.js — Service Worker: orchestration, state, tab management, message routing
  2. importScripts('data/names.js', 'hotmail-utils.js', 'content/activation-utils.js');
  3. const {
  4. buildHotmailGraphMessagesUrl,
  5. extractVerificationCodeFromMessage,
  6. filterHotmailAccountsByUsage,
  7. getLatestHotmailMessage,
  8. getHotmailGraphRequestConfig,
  9. getHotmailVerificationPollConfig,
  10. getHotmailVerificationRequestTimestamp,
  11. normalizeHotmailMailApiMessages,
  12. pickHotmailAccountForRun,
  13. pickVerificationMessage,
  14. pickVerificationMessageWithFallback,
  15. pickVerificationMessageWithTimeFallback,
  16. shouldClearHotmailCurrentSelection,
  17. } = self.HotmailUtils;
  18. const {
  19. isRecoverableStep9AuthFailure,
  20. } = self.MultiPageActivationUtils;
  21. const buildHotmailMailApiLatestUrl = buildHotmailGraphMessagesUrl;
  22. const getHotmailMailApiRequestConfig = getHotmailGraphRequestConfig;
  23. const LOG_PREFIX = '[MultiPage:bg]';
  24. const DUCK_AUTOFILL_URL = 'https://duckduckgo.com/email/settings/autofill';
  25. const HOTMAIL_PROVIDER = 'hotmail-api';
  26. const HOTMAIL_MAILBOXES = ['INBOX', 'Junk'];
  27. const STOP_ERROR_MESSAGE = '流程已被用户停止。';
  28. const HUMAN_STEP_DELAY_MIN = 700;
  29. const HUMAN_STEP_DELAY_MAX = 2200;
  30. const STEP7_RESTART_MAX_ROUNDS = 8;
  31. const AUTO_RUN_ALARM_NAME = 'scheduled-auto-run';
  32. const AUTO_RUN_DELAY_MIN_MINUTES = 1;
  33. const AUTO_RUN_DELAY_MAX_MINUTES = 1440;
  34. initializeSessionStorageAccess();
  35. // ============================================================
  36. // 状态管理(chrome.storage.session + chrome.storage.local)
  37. // ============================================================
  38. const PERSISTED_SETTING_DEFAULTS = {
  39. vpsUrl: '', // VPS 面板地址,可手动填写。
  40. vpsPassword: '', // VPS 面板登录密码,可手动填写。
  41. customPassword: '', // 自定义账号密码;留空时由程序自动生成随机密码。
  42. autoRunSkipFailures: false, // 自动运行遇到失败步骤后,是否继续执行后续流程。
  43. autoRunDelayEnabled: false, // 自动运行是否启用启动前倒计时。
  44. autoRunDelayMinutes: 30, // 自动运行倒计时分钟数。
  45. mailProvider: '163', // 验证码邮箱来源(163 / 163-vip / qq / inbucket)。
  46. emailGenerator: 'duck', // 注册邮箱生成方式:duck / cloudflare。
  47. inbucketHost: '', // 仅当 mailProvider 为 inbucket 时填写 Inbucket 地址,其他情况保持为空。
  48. inbucketMailbox: '', // 仅当 mailProvider 为 inbucket 时填写邮箱名,其他情况保持为空。
  49. cloudflareDomain: '', // 仅当 emailGenerator=cloudflare 时填写自定义域名。
  50. cloudflareDomains: [], // Cloudflare 可选域名列表。
  51. hotmailAccounts: [],
  52. };
  53. const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);
  54. const DEFAULT_STATE = {
  55. currentStep: 0, // 当前流程执行到的步骤编号。
  56. stepStatuses: {
  57. 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending', // 运行时步骤状态映射,不要手动预填。
  58. 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
  59. },
  60. oauthUrl: null, // 运行时抓取到的 OAuth 地址,不要手动预填。
  61. email: null, // 运行时邮箱,由程序自动获取并写入,不能手动预填。
  62. password: null, // 运行时实际密码,由 customPassword 或程序自动生成后写入。
  63. accounts: [], // 已生成账号记录:{ email, password, createdAt }。
  64. lastEmailTimestamp: null, // 最近一次获取到邮箱数据的运行时时间戳。
  65. lastSignupCode: null, // 注册验证码,运行时由程序自动读取并写入。
  66. lastLoginCode: null, // 登录验证码,运行时由程序自动读取并写入。
  67. localhostUrl: null, // 运行时捕获到的 localhost 回调地址,不要手动预填。
  68. flowStartTime: null, // 当前流程开始时间。
  69. tabRegistry: {}, // 程序维护的标签页注册表。
  70. sourceLastUrls: {}, // 各来源页面最近一次打开的地址记录。
  71. logs: [], // 侧边栏展示的运行日志。
  72. ...PERSISTED_SETTING_DEFAULTS, // 合并 chrome.storage.local 中持久化保存的用户配置。
  73. autoRunning: false, // 当前是否处于自动运行中。
  74. autoRunPhase: 'idle', // 当前自动运行阶段。
  75. autoRunCurrentRun: 0, // 自动运行当前执行到第几轮。
  76. autoRunTotalRuns: 1, // 自动运行计划总轮数。
  77. autoRunAttemptRun: 0, // 当前轮次的重试序号。
  78. scheduledAutoRunAt: null, // 自动运行计划启动时间戳。
  79. scheduledAutoRunPlan: null, // 自动运行计划参数快照。
  80. signupVerificationRequestedAt: null,
  81. loginVerificationRequestedAt: null,
  82. currentHotmailAccountId: null,
  83. };
  84. function normalizeAutoRunDelayMinutes(value) {
  85. const numeric = Number(value);
  86. if (!Number.isFinite(numeric)) {
  87. return PERSISTED_SETTING_DEFAULTS.autoRunDelayMinutes;
  88. }
  89. return Math.min(
  90. AUTO_RUN_DELAY_MAX_MINUTES,
  91. Math.max(AUTO_RUN_DELAY_MIN_MINUTES, Math.floor(numeric))
  92. );
  93. }
  94. function normalizeRunCount(value) {
  95. const numeric = Number(value);
  96. if (!Number.isFinite(numeric)) {
  97. return 1;
  98. }
  99. return Math.min(50, Math.max(1, Math.floor(numeric)));
  100. }
  101. function normalizeScheduledAutoRunPlan(plan) {
  102. if (!plan || typeof plan !== 'object') {
  103. return null;
  104. }
  105. return {
  106. totalRuns: normalizeRunCount(plan.totalRuns),
  107. autoRunSkipFailures: Boolean(plan.autoRunSkipFailures),
  108. mode: plan.mode === 'continue' ? 'continue' : 'restart',
  109. };
  110. }
  111. function normalizeEmailGenerator(value = '') {
  112. return String(value || '').trim().toLowerCase() === 'cloudflare' ? 'cloudflare' : 'duck';
  113. }
  114. function normalizeCloudflareDomain(rawValue = '') {
  115. let value = String(rawValue || '').trim().toLowerCase();
  116. if (!value) return '';
  117. value = value.replace(/^@+/, '');
  118. value = value.replace(/^https?:\/\//, '');
  119. value = value.replace(/\/.*$/, '');
  120. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(value)) return '';
  121. return value;
  122. }
  123. async function getPersistedSettings() {
  124. const stored = await chrome.storage.local.get(PERSISTED_SETTING_KEYS);
  125. return {
  126. ...PERSISTED_SETTING_DEFAULTS,
  127. ...stored,
  128. autoRunSkipFailures: Boolean(stored.autoRunSkipFailures ?? PERSISTED_SETTING_DEFAULTS.autoRunSkipFailures),
  129. autoRunDelayEnabled: Boolean(stored.autoRunDelayEnabled ?? PERSISTED_SETTING_DEFAULTS.autoRunDelayEnabled),
  130. autoRunDelayMinutes: normalizeAutoRunDelayMinutes(stored.autoRunDelayMinutes ?? PERSISTED_SETTING_DEFAULTS.autoRunDelayMinutes),
  131. emailGenerator: normalizeEmailGenerator(stored.emailGenerator ?? PERSISTED_SETTING_DEFAULTS.emailGenerator),
  132. hotmailAccounts: normalizeHotmailAccounts(stored.hotmailAccounts),
  133. };
  134. }
  135. async function getState() {
  136. const [state, persistedSettings] = await Promise.all([
  137. chrome.storage.session.get(null),
  138. getPersistedSettings(),
  139. ]);
  140. return { ...DEFAULT_STATE, ...persistedSettings, ...state };
  141. }
  142. async function initializeSessionStorageAccess() {
  143. try {
  144. if (chrome.storage?.session?.setAccessLevel) {
  145. await chrome.storage.session.setAccessLevel({
  146. accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS',
  147. });
  148. console.log(LOG_PREFIX, 'Enabled storage.session for content scripts');
  149. }
  150. } catch (err) {
  151. console.warn(LOG_PREFIX, 'Failed to enable storage.session for content scripts:', err?.message || err);
  152. }
  153. }
  154. async function setState(updates) {
  155. console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
  156. if (Object.keys(updates || {}).length > 0) {
  157. await chrome.storage.session.set(updates);
  158. }
  159. }
  160. async function setPersistentSettings(updates) {
  161. const persistedUpdates = {};
  162. for (const key of PERSISTED_SETTING_KEYS) {
  163. if (updates[key] !== undefined) {
  164. if (key === 'autoRunSkipFailures' || key === 'autoRunDelayEnabled') {
  165. persistedUpdates[key] = Boolean(updates[key]);
  166. } else if (key === 'autoRunDelayMinutes') {
  167. persistedUpdates[key] = normalizeAutoRunDelayMinutes(updates[key]);
  168. } else if (key === 'hotmailAccounts') {
  169. persistedUpdates[key] = normalizeHotmailAccounts(updates[key]);
  170. } else {
  171. persistedUpdates[key] = updates[key];
  172. }
  173. }
  174. }
  175. if (Object.keys(persistedUpdates).length > 0) {
  176. await chrome.storage.local.set(persistedUpdates);
  177. }
  178. }
  179. function broadcastDataUpdate(payload) {
  180. chrome.runtime.sendMessage({
  181. type: 'DATA_UPDATED',
  182. payload,
  183. }).catch(() => { });
  184. }
  185. async function setEmailState(email) {
  186. await setState({ email });
  187. broadcastDataUpdate({ email });
  188. if (email) {
  189. await resumeAutoRunIfWaitingForEmail();
  190. }
  191. }
  192. async function setPasswordState(password) {
  193. await setState({ password });
  194. broadcastDataUpdate({ password });
  195. }
  196. async function resetState() {
  197. console.log(LOG_PREFIX, 'Resetting all state');
  198. // Preserve settings and persistent data across resets
  199. const [prev, persistedSettings] = await Promise.all([
  200. chrome.storage.session.get([
  201. 'seenCodes',
  202. 'seenInbucketMailIds',
  203. 'accounts',
  204. 'tabRegistry',
  205. 'sourceLastUrls',
  206. ]),
  207. getPersistedSettings(),
  208. ]);
  209. await chrome.storage.session.clear();
  210. await chrome.storage.session.set({
  211. ...DEFAULT_STATE,
  212. ...persistedSettings,
  213. seenCodes: prev.seenCodes || [],
  214. seenInbucketMailIds: prev.seenInbucketMailIds || [],
  215. accounts: prev.accounts || [],
  216. tabRegistry: prev.tabRegistry || {},
  217. sourceLastUrls: prev.sourceLastUrls || {},
  218. });
  219. }
  220. /**
  221. * Generate a random password: 14 chars, mix of uppercase, lowercase, digits, symbols.
  222. */
  223. function generatePassword() {
  224. const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  225. const lower = 'abcdefghjkmnpqrstuvwxyz';
  226. const digits = '23456789';
  227. const symbols = '!@#$%&*?';
  228. const all = upper + lower + digits + symbols;
  229. // Ensure at least one of each type
  230. let pw = '';
  231. pw += upper[Math.floor(Math.random() * upper.length)];
  232. pw += lower[Math.floor(Math.random() * lower.length)];
  233. pw += digits[Math.floor(Math.random() * digits.length)];
  234. pw += symbols[Math.floor(Math.random() * symbols.length)];
  235. // Fill remaining 10 chars
  236. for (let i = 0; i < 10; i++) {
  237. pw += all[Math.floor(Math.random() * all.length)];
  238. }
  239. // Shuffle
  240. return pw.split('').sort(() => Math.random() - 0.5).join('');
  241. }
  242. function normalizeHotmailAccount(account = {}) {
  243. const normalizedLastAuthAt = Number.isFinite(Number(account.lastAuthAt)) ? Number(account.lastAuthAt) : 0;
  244. const normalizedStatus = String(
  245. account.status
  246. || (normalizedLastAuthAt > 0 || account.accessToken ? 'authorized' : 'pending')
  247. );
  248. return {
  249. id: String(account.id || crypto.randomUUID()),
  250. email: String(account.email || '').trim(),
  251. password: String(account.password || ''),
  252. clientId: String(account.clientId || '').trim(),
  253. accessToken: String(account.accessToken || ''),
  254. refreshToken: String(account.refreshToken || ''),
  255. expiresAt: Number.isFinite(Number(account.expiresAt)) ? Number(account.expiresAt) : 0,
  256. status: normalizedStatus,
  257. enabled: account.enabled !== undefined ? Boolean(account.enabled) : true,
  258. used: Boolean(account.used),
  259. lastUsedAt: Number.isFinite(Number(account.lastUsedAt)) ? Number(account.lastUsedAt) : 0,
  260. lastAuthAt: normalizedLastAuthAt,
  261. lastError: String(account.lastError || ''),
  262. };
  263. }
  264. function normalizeHotmailAccounts(accounts) {
  265. if (!Array.isArray(accounts)) return [];
  266. const deduped = new Map();
  267. for (const account of accounts) {
  268. const normalized = normalizeHotmailAccount(account);
  269. if (!normalized.email && !normalized.id) continue;
  270. deduped.set(normalized.id, normalized);
  271. }
  272. return [...deduped.values()];
  273. }
  274. function findHotmailAccount(accounts, accountId) {
  275. return normalizeHotmailAccounts(accounts).find((account) => account.id === accountId) || null;
  276. }
  277. function isHotmailProvider(stateOrProvider) {
  278. const provider = typeof stateOrProvider === 'string'
  279. ? stateOrProvider
  280. : stateOrProvider?.mailProvider;
  281. return provider === HOTMAIL_PROVIDER;
  282. }
  283. async function syncHotmailAccounts(accounts) {
  284. const normalized = normalizeHotmailAccounts(accounts);
  285. await setPersistentSettings({ hotmailAccounts: normalized });
  286. await setState({ hotmailAccounts: normalized });
  287. broadcastDataUpdate({ hotmailAccounts: normalized });
  288. return normalized;
  289. }
  290. async function upsertHotmailAccount(input) {
  291. const state = await getState();
  292. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  293. const normalizedEmail = String(input?.email || '').trim().toLowerCase();
  294. const existing = input?.id
  295. ? findHotmailAccount(accounts, input.id)
  296. : accounts.find((account) => account.email.toLowerCase() === normalizedEmail) || null;
  297. const credentialsChanged = !existing
  298. || (input?.clientId !== undefined && String(input.clientId).trim() !== existing.clientId)
  299. || (input?.refreshToken !== undefined && String(input.refreshToken).trim() !== existing.refreshToken)
  300. || (input?.email !== undefined && String(input.email).trim().toLowerCase() !== existing.email.toLowerCase());
  301. const normalized = normalizeHotmailAccount({
  302. ...(existing || {}),
  303. ...(credentialsChanged ? {
  304. accessToken: '',
  305. expiresAt: 0,
  306. status: 'pending',
  307. lastAuthAt: 0,
  308. lastError: '',
  309. } : {}),
  310. ...input,
  311. id: input?.id || existing?.id || crypto.randomUUID(),
  312. });
  313. const nextAccounts = existing
  314. ? accounts.map((account) => (account.id === normalized.id ? normalized : account))
  315. : [...accounts, normalized];
  316. await syncHotmailAccounts(nextAccounts);
  317. return normalized;
  318. }
  319. async function deleteHotmailAccount(accountId) {
  320. const state = await getState();
  321. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  322. const nextAccounts = accounts.filter((account) => account.id !== accountId);
  323. await syncHotmailAccounts(nextAccounts);
  324. if (state.currentHotmailAccountId === accountId) {
  325. await setState({ currentHotmailAccountId: null });
  326. if (isHotmailProvider(state)) {
  327. await setEmailState(null);
  328. }
  329. broadcastDataUpdate({ currentHotmailAccountId: null });
  330. }
  331. }
  332. async function deleteHotmailAccounts(mode = 'all') {
  333. const state = await getState();
  334. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  335. const targets = filterHotmailAccountsByUsage(accounts, mode);
  336. const targetIds = new Set(targets.map((account) => account.id));
  337. const nextAccounts = mode === 'used'
  338. ? accounts.filter((account) => !targetIds.has(account.id))
  339. : [];
  340. await syncHotmailAccounts(nextAccounts);
  341. if (state.currentHotmailAccountId && targetIds.has(state.currentHotmailAccountId)) {
  342. await setState({ currentHotmailAccountId: null });
  343. if (isHotmailProvider(state)) {
  344. await setEmailState(null);
  345. }
  346. broadcastDataUpdate({ currentHotmailAccountId: null });
  347. }
  348. return {
  349. deletedCount: targets.length,
  350. remainingCount: nextAccounts.length,
  351. };
  352. }
  353. async function patchHotmailAccount(accountId, updates = {}) {
  354. const state = await getState();
  355. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  356. const account = findHotmailAccount(accounts, accountId);
  357. if (!account) {
  358. throw new Error('未找到对应的 Hotmail 账号。');
  359. }
  360. const nextAccount = normalizeHotmailAccount({
  361. ...account,
  362. ...updates,
  363. id: account.id,
  364. });
  365. await syncHotmailAccounts(accounts.map((item) => (item.id === account.id ? nextAccount : item)));
  366. if (state.currentHotmailAccountId === account.id && shouldClearHotmailCurrentSelection(nextAccount)) {
  367. await setState({ currentHotmailAccountId: null });
  368. broadcastDataUpdate({ currentHotmailAccountId: null });
  369. if (isHotmailProvider(state)) {
  370. await setEmailState(null);
  371. }
  372. }
  373. return nextAccount;
  374. }
  375. async function setCurrentHotmailAccount(accountId, options = {}) {
  376. const { markUsed = false, syncEmail = true } = options;
  377. const state = await getState();
  378. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  379. const account = findHotmailAccount(accounts, accountId);
  380. if (!account) {
  381. throw new Error('未找到对应的 Hotmail 账号。');
  382. }
  383. if (markUsed) {
  384. account.lastUsedAt = Date.now();
  385. await syncHotmailAccounts(accounts.map((item) => (item.id === account.id ? account : item)));
  386. }
  387. await setState({ currentHotmailAccountId: account.id });
  388. broadcastDataUpdate({ currentHotmailAccountId: account.id });
  389. if (syncEmail) {
  390. await setEmailState(account.email || null);
  391. }
  392. return account;
  393. }
  394. async function ensureHotmailAccountForFlow(options = {}) {
  395. const { allowAllocate = true, markUsed = false, preferredAccountId = null } = options;
  396. const state = await getState();
  397. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  398. const isAccountAllocatable = (candidate) => Boolean(candidate)
  399. && candidate.status === 'authorized'
  400. && !candidate.used
  401. && Boolean(candidate.refreshToken);
  402. let account = null;
  403. if (preferredAccountId) {
  404. account = findHotmailAccount(accounts, preferredAccountId);
  405. }
  406. if (!account && state.currentHotmailAccountId) {
  407. account = findHotmailAccount(accounts, state.currentHotmailAccountId);
  408. }
  409. if ((!account || !isAccountAllocatable(account)) && allowAllocate) {
  410. account = pickHotmailAccountForRun(accounts, {});
  411. }
  412. if (!account) {
  413. throw new Error('没有可用的 Hotmail 账号。请先在侧边栏添加至少一个带刷新令牌(refresh token)的账号。');
  414. }
  415. if (!isAccountAllocatable(account)) {
  416. throw new Error(`Hotmail 账号 ${account.email || account.id} 尚未就绪,无法读取邮件。`);
  417. }
  418. return setCurrentHotmailAccount(account.id, { markUsed, syncEmail: true });
  419. }
  420. async function requestHotmailMailApiLegacy(account, mailbox = 'INBOX') {
  421. if (!account?.email) {
  422. throw new Error('Hotmail 账号缺少邮箱地址。');
  423. }
  424. if (!account?.clientId) {
  425. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少客户端 ID。`);
  426. }
  427. if (!account?.refreshToken) {
  428. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少刷新令牌(refresh token)。`);
  429. }
  430. const url = buildHotmailMailApiLatestUrl({
  431. clientId: account.clientId,
  432. email: account.email,
  433. refreshToken: account.refreshToken,
  434. mailbox,
  435. responseType: 'json',
  436. });
  437. const { timeoutMs } = getHotmailMailApiRequestConfig();
  438. const controller = new AbortController();
  439. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
  440. let response;
  441. try {
  442. response = await fetch(url, { method: 'GET', signal: controller.signal });
  443. } catch (err) {
  444. if (err?.name === 'AbortError') {
  445. throw new Error(`Hotmail API 请求超时(>${Math.round(timeoutMs / 1000)} 秒):${mailbox}`);
  446. }
  447. throw new Error(`Hotmail API 请求失败:${err.message}`);
  448. } finally {
  449. clearTimeout(timeoutId);
  450. }
  451. const text = await response.text();
  452. let payload = {};
  453. try {
  454. payload = text ? JSON.parse(text) : {};
  455. } catch {
  456. payload = { raw: text };
  457. }
  458. if (!response.ok) {
  459. const errorText = payload?.message || payload?.error || payload?.msg || text || `HTTP ${response.status}`;
  460. throw new Error(`Hotmail API 请求失败:${errorText}`);
  461. }
  462. if (payload && payload.success === false) {
  463. const errorText = payload?.message || payload?.msg || payload?.error || '未知错误';
  464. throw new Error(`Hotmail API 返回失败:${errorText}`);
  465. }
  466. return {
  467. mailbox,
  468. payload,
  469. messages: normalizeHotmailMailApiMessages(payload?.data),
  470. nextRefreshToken: String(payload?.new_refresh_token || payload?.newRefreshToken || '').trim(),
  471. };
  472. }
  473. function applyHotmailApiResultToAccountLegacy(account, apiResult) {
  474. const nextRefreshToken = String(apiResult?.nextRefreshToken || '').trim();
  475. return {
  476. ...account,
  477. accessToken: '',
  478. expiresAt: 0,
  479. refreshToken: nextRefreshToken || account.refreshToken,
  480. status: 'authorized',
  481. lastAuthAt: Date.now(),
  482. lastError: '',
  483. };
  484. }
  485. async function fetchHotmailMailboxMessagesLegacy(account, mailboxes = HOTMAIL_MAILBOXES) {
  486. let workingAccount = normalizeHotmailAccount(account);
  487. const mailboxResults = [];
  488. for (const mailbox of mailboxes) {
  489. const result = await requestHotmailMailApiLegacy(workingAccount, mailbox);
  490. workingAccount = applyHotmailApiResultToAccountLegacy(workingAccount, result);
  491. mailboxResults.push({
  492. mailbox,
  493. count: result.messages.length,
  494. messages: result.messages.map((message) => ({ ...message, mailbox })),
  495. });
  496. }
  497. const savedAccount = await upsertHotmailAccount(workingAccount);
  498. return {
  499. account: savedAccount,
  500. mailboxResults,
  501. messages: mailboxResults.flatMap((item) => item.messages),
  502. };
  503. }
  504. function isHotmailAccessTokenUsable(account, now = Date.now()) {
  505. return Boolean(account?.accessToken)
  506. && Number(account?.expiresAt || 0) > now + 60_000;
  507. }
  508. async function refreshHotmailAccessToken(account) {
  509. if (!account?.email) {
  510. throw new Error('Hotmail 账号缺少邮箱地址。');
  511. }
  512. if (!account?.clientId) {
  513. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少客户端 ID。`);
  514. }
  515. if (!account?.refreshToken) {
  516. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少刷新令牌(refresh token)。`);
  517. }
  518. const { timeoutMs, scopes, tokenUrl } = getHotmailGraphRequestConfig();
  519. const controller = new AbortController();
  520. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
  521. const formData = new URLSearchParams();
  522. formData.set('client_id', account.clientId);
  523. formData.set('grant_type', 'refresh_token');
  524. formData.set('refresh_token', account.refreshToken);
  525. formData.set('scope', scopes.join(' '));
  526. let response;
  527. try {
  528. response = await fetch(tokenUrl, {
  529. method: 'POST',
  530. headers: {
  531. 'Content-Type': 'application/x-www-form-urlencoded',
  532. },
  533. body: formData.toString(),
  534. signal: controller.signal,
  535. });
  536. } catch (err) {
  537. const error = new Error(
  538. err?.name === 'AbortError'
  539. ? `Hotmail 令牌刷新超时(>${Math.round(timeoutMs / 1000)} 秒)`
  540. : `Hotmail 令牌刷新失败:${err.message}`
  541. );
  542. error.code = 'HOTMAIL_TOKEN_REFRESH_FAILED';
  543. throw error;
  544. } finally {
  545. clearTimeout(timeoutId);
  546. }
  547. const text = await response.text();
  548. let payload = {};
  549. try {
  550. payload = text ? JSON.parse(text) : {};
  551. } catch {
  552. payload = { raw: text };
  553. }
  554. if (!response.ok || !payload?.access_token) {
  555. const errorText = payload?.error_description || payload?.error?.message || payload?.error || payload?.message || text || `HTTP ${response.status}`;
  556. const error = new Error(`Hotmail 令牌刷新失败:${errorText}`);
  557. error.code = 'HOTMAIL_TOKEN_REFRESH_FAILED';
  558. throw error;
  559. }
  560. const expiresInSeconds = Math.max(60, Number(payload.expires_in || payload.expiresIn || 0) || 3600);
  561. return normalizeHotmailAccount({
  562. ...account,
  563. accessToken: String(payload.access_token || ''),
  564. refreshToken: String(payload.refresh_token || '').trim() || account.refreshToken,
  565. expiresAt: Date.now() + expiresInSeconds * 1000,
  566. status: 'authorized',
  567. lastAuthAt: Date.now(),
  568. lastError: '',
  569. });
  570. }
  571. async function requestHotmailGraphMessages(account, mailbox = 'INBOX') {
  572. const { timeoutMs, pageSize, messageFields } = getHotmailGraphRequestConfig();
  573. const controller = new AbortController();
  574. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
  575. const url = buildHotmailGraphMessagesUrl({
  576. mailbox,
  577. top: pageSize,
  578. selectFields: messageFields,
  579. });
  580. let response;
  581. try {
  582. response = await fetch(url, {
  583. method: 'GET',
  584. headers: {
  585. Accept: 'application/json',
  586. Authorization: `Bearer ${account.accessToken}`,
  587. },
  588. signal: controller.signal,
  589. });
  590. } catch (err) {
  591. const error = new Error(
  592. err?.name === 'AbortError'
  593. ? `Hotmail 邮件请求超时(>${Math.round(timeoutMs / 1000)} 秒):${mailbox}`
  594. : `Hotmail 邮件请求失败:${err.message}`
  595. );
  596. error.code = 'HOTMAIL_GRAPH_REQUEST_FAILED';
  597. throw error;
  598. } finally {
  599. clearTimeout(timeoutId);
  600. }
  601. const text = await response.text();
  602. let payload = {};
  603. try {
  604. payload = text ? JSON.parse(text) : {};
  605. } catch {
  606. payload = { raw: text };
  607. }
  608. if (!response.ok) {
  609. const errorText = payload?.error?.message || payload?.error_description || payload?.message || text || `HTTP ${response.status}`;
  610. const error = new Error(`Hotmail 邮件请求失败:${errorText}`);
  611. error.code = response.status === 401 || response.status === 403
  612. ? 'HOTMAIL_GRAPH_AUTH_FAILED'
  613. : 'HOTMAIL_GRAPH_REQUEST_FAILED';
  614. throw error;
  615. }
  616. return {
  617. mailbox,
  618. payload,
  619. messages: normalizeHotmailMailApiMessages(payload?.value),
  620. };
  621. }
  622. function buildHotmailAuthFailureAccount(account, errorMessage) {
  623. return normalizeHotmailAccount({
  624. ...account,
  625. accessToken: '',
  626. expiresAt: 0,
  627. status: 'error',
  628. lastError: String(errorMessage || ''),
  629. });
  630. }
  631. async function fetchHotmailMailboxMessages(account, mailboxes = HOTMAIL_MAILBOXES) {
  632. let workingAccount = normalizeHotmailAccount(account);
  633. const mailboxResults = [];
  634. try {
  635. if (!isHotmailAccessTokenUsable(workingAccount)) {
  636. workingAccount = await refreshHotmailAccessToken(workingAccount);
  637. }
  638. for (const mailbox of mailboxes) {
  639. let result;
  640. try {
  641. result = await requestHotmailGraphMessages(workingAccount, mailbox);
  642. } catch (err) {
  643. if (err?.code !== 'HOTMAIL_GRAPH_AUTH_FAILED') {
  644. throw err;
  645. }
  646. workingAccount = await refreshHotmailAccessToken({
  647. ...workingAccount,
  648. accessToken: '',
  649. expiresAt: 0,
  650. });
  651. result = await requestHotmailGraphMessages(workingAccount, mailbox);
  652. }
  653. mailboxResults.push({
  654. mailbox,
  655. count: result.messages.length,
  656. messages: result.messages.map((message) => ({ ...message, mailbox })),
  657. });
  658. }
  659. } catch (err) {
  660. if (err?.code === 'HOTMAIL_TOKEN_REFRESH_FAILED' || err?.code === 'HOTMAIL_GRAPH_AUTH_FAILED') {
  661. const failedAccount = buildHotmailAuthFailureAccount(workingAccount, err.message);
  662. await upsertHotmailAccount(failedAccount);
  663. }
  664. throw err;
  665. }
  666. const savedAccount = await upsertHotmailAccount(workingAccount);
  667. return {
  668. account: savedAccount,
  669. mailboxResults,
  670. messages: mailboxResults.flatMap((item) => item.messages),
  671. };
  672. }
  673. async function verifyHotmailAccount(accountId) {
  674. const state = await getState();
  675. const account = findHotmailAccount(state.hotmailAccounts, accountId);
  676. if (!account) {
  677. throw new Error('未找到需要校验的 Hotmail 账号。');
  678. }
  679. const result = await fetchHotmailMailboxMessages(account, ['INBOX']);
  680. return {
  681. account: result.account,
  682. messageCount: result.mailboxResults[0]?.count || 0,
  683. };
  684. }
  685. async function testHotmailAccountMailAccess(accountId) {
  686. const state = await getState();
  687. const account = findHotmailAccount(state.hotmailAccounts, accountId);
  688. if (!account) {
  689. throw new Error('未找到需要测试的 Hotmail 账号。');
  690. }
  691. const result = await fetchHotmailMailboxMessages(account, HOTMAIL_MAILBOXES);
  692. const latestMessage = getLatestHotmailMessage(result.messages);
  693. const latestCode = latestMessage ? extractVerificationCodeFromMessage(latestMessage) : null;
  694. return {
  695. account: result.account,
  696. accountId: result.account.id,
  697. email: result.account.email,
  698. messageCount: result.messages.length,
  699. latestSubject: latestMessage?.subject || '',
  700. latestMailbox: latestMessage?.mailbox || '',
  701. latestCode: latestCode || '',
  702. inboxCount: result.mailboxResults.find((item) => item.mailbox === 'INBOX')?.count || 0,
  703. junkCount: result.mailboxResults.find((item) => item.mailbox === 'Junk')?.count || 0,
  704. };
  705. }
  706. async function pollHotmailVerificationCode(step, state, pollPayload = {}) {
  707. await addLog(`步骤 ${step}:正在确定 Hotmail 收信账号...`, 'info');
  708. let account = await ensureHotmailAccountForFlow({
  709. allowAllocate: true,
  710. markUsed: false,
  711. preferredAccountId: state.currentHotmailAccountId || null,
  712. });
  713. await addLog(`步骤 ${step}:当前使用 Hotmail 账号 ${account.email} 轮询收件箱。`, 'info');
  714. const maxAttempts = Number(pollPayload.maxAttempts) || 5;
  715. const intervalMs = Number(pollPayload.intervalMs) || 3000;
  716. let lastError = null;
  717. function summarizeMessagesForLog(messages) {
  718. return (messages || [])
  719. .slice()
  720. .sort((left, right) => {
  721. const leftTime = Date.parse(left.receivedDateTime || '') || 0;
  722. const rightTime = Date.parse(right.receivedDateTime || '') || 0;
  723. return rightTime - leftTime;
  724. })
  725. .slice(0, 3)
  726. .map((message) => {
  727. const receivedAt = message?.receivedDateTime || '未知时间';
  728. const sender = message?.from?.emailAddress?.address || '未知发件人';
  729. const subject = message?.subject || '(无主题)';
  730. const preview = String(message?.bodyPreview || '').replace(/\s+/g, ' ').trim().slice(0, 80);
  731. return `[${message.mailbox || 'INBOX'}] ${receivedAt} | ${sender} | ${subject} | ${preview}`;
  732. })
  733. .join(' || ');
  734. }
  735. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  736. throwIfStopped();
  737. try {
  738. await addLog(`步骤 ${step}:正在轮询 Hotmail 邮件(${attempt}/${maxAttempts})...`, 'info');
  739. const fetchResult = await fetchHotmailMailboxMessages(account, HOTMAIL_MAILBOXES);
  740. account = fetchResult.account;
  741. const matchResult = pickVerificationMessageWithTimeFallback(fetchResult.messages, {
  742. afterTimestamp: pollPayload.filterAfterTimestamp || 0,
  743. senderFilters: pollPayload.senderFilters || [],
  744. subjectFilters: pollPayload.subjectFilters || [],
  745. excludeCodes: pollPayload.excludeCodes || [],
  746. });
  747. const match = matchResult.match;
  748. if (match?.code) {
  749. const mailboxLabel = match.message?.mailbox || 'INBOX';
  750. if (matchResult.usedRelaxedFilters) {
  751. const fallbackLabel = matchResult.usedTimeFallback ? '宽松匹配 + 时间回退' : '宽松匹配';
  752. await addLog(`步骤 ${step}:严格规则未命中,已改用 ${fallbackLabel} 并命中 Hotmail ${mailboxLabel} 验证码。`, 'warn');
  753. }
  754. await addLog(`步骤 ${step}:已在 Hotmail ${mailboxLabel} 中找到验证码:${match.code}`, 'ok');
  755. return {
  756. ok: true,
  757. code: match.code,
  758. emailTimestamp: match.receivedAt || Date.now(),
  759. mailId: match.message?.id || '',
  760. };
  761. }
  762. lastError = new Error(`步骤 ${step}:暂未在 Hotmail 收件箱中找到匹配验证码(${attempt}/${maxAttempts})。`);
  763. await addLog(lastError.message, attempt === maxAttempts ? 'warn' : 'info');
  764. const mailSummary = summarizeMessagesForLog(fetchResult.messages);
  765. if (mailSummary) {
  766. await addLog(`步骤 ${step}:最近邮件样本:${mailSummary}`, 'info');
  767. }
  768. } catch (err) {
  769. lastError = err;
  770. await addLog(`步骤 ${step}:Hotmail 收件箱轮询失败:${err.message}`, 'warn');
  771. }
  772. if (attempt < maxAttempts) {
  773. await sleepWithStop(intervalMs);
  774. }
  775. }
  776. throw lastError || new Error(`步骤 ${step}:未在 Hotmail 收件箱中找到新的匹配验证码。`);
  777. }
  778. // ============================================================
  779. // Tab Registry
  780. // ============================================================
  781. async function getTabRegistry() {
  782. const state = await getState();
  783. return state.tabRegistry || {};
  784. }
  785. async function registerTab(source, tabId) {
  786. const registry = await getTabRegistry();
  787. registry[source] = { tabId, ready: true };
  788. await setState({ tabRegistry: registry });
  789. console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
  790. }
  791. async function isTabAlive(source) {
  792. const registry = await getTabRegistry();
  793. const entry = registry[source];
  794. if (!entry) return false;
  795. try {
  796. await chrome.tabs.get(entry.tabId);
  797. return true;
  798. } catch {
  799. // Tab no longer exists — clean up registry
  800. registry[source] = null;
  801. await setState({ tabRegistry: registry });
  802. return false;
  803. }
  804. }
  805. async function getTabId(source) {
  806. const registry = await getTabRegistry();
  807. return registry[source]?.tabId || null;
  808. }
  809. function parseUrlSafely(rawUrl) {
  810. if (!rawUrl) return null;
  811. try {
  812. return new URL(rawUrl);
  813. } catch {
  814. return null;
  815. }
  816. }
  817. function isSignupPageHost(hostname = '') {
  818. return ['auth0.openai.com', 'auth.openai.com', 'accounts.openai.com'].includes(hostname);
  819. }
  820. function is163MailHost(hostname = '') {
  821. return hostname === 'mail.163.com'
  822. || hostname.endsWith('.mail.163.com')
  823. || hostname === 'webmail.vip.163.com';
  824. }
  825. function isLocalhostOAuthCallbackUrl(rawUrl) {
  826. const parsed = parseUrlSafely(rawUrl);
  827. if (!parsed) return false;
  828. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  829. if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
  830. if (!['/auth/callback', '/codex/callback'].includes(parsed.pathname)) return false;
  831. const code = (parsed.searchParams.get('code') || '').trim();
  832. const state = (parsed.searchParams.get('state') || '').trim();
  833. return Boolean(code && state);
  834. }
  835. function isLocalCpaUrl(rawUrl) {
  836. const parsed = parseUrlSafely(rawUrl);
  837. if (!parsed) return false;
  838. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  839. return ['localhost', '127.0.0.1'].includes(parsed.hostname);
  840. }
  841. function shouldBypassStep9ForLocalCpa(state) {
  842. return Boolean(state?.localhostUrl) && isLocalCpaUrl(state?.vpsUrl);
  843. }
  844. function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
  845. const candidate = parseUrlSafely(candidateUrl);
  846. if (!candidate) return false;
  847. const reference = parseUrlSafely(referenceUrl);
  848. switch (source) {
  849. case 'signup-page':
  850. return isSignupPageHost(candidate.hostname);
  851. case 'duck-mail':
  852. return candidate.hostname === 'duckduckgo.com' && candidate.pathname.startsWith('/email/');
  853. case 'qq-mail':
  854. return candidate.hostname === 'mail.qq.com' || candidate.hostname === 'wx.mail.qq.com';
  855. case 'mail-163':
  856. return is163MailHost(candidate.hostname);
  857. case 'inbucket-mail':
  858. return Boolean(reference)
  859. && candidate.origin === reference.origin
  860. && candidate.pathname.startsWith('/m/');
  861. case 'vps-panel':
  862. return Boolean(reference)
  863. && candidate.origin === reference.origin
  864. && candidate.pathname === reference.pathname;
  865. default:
  866. return false;
  867. }
  868. }
  869. async function rememberSourceLastUrl(source, url) {
  870. if (!source || !url) return;
  871. const state = await getState();
  872. const sourceLastUrls = { ...(state.sourceLastUrls || {}) };
  873. sourceLastUrls[source] = url;
  874. await setState({ sourceLastUrls });
  875. }
  876. async function closeConflictingTabsForSource(source, currentUrl, options = {}) {
  877. const { excludeTabIds = [] } = options;
  878. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  879. const state = await getState();
  880. const lastUrl = state.sourceLastUrls?.[source];
  881. const referenceUrls = [currentUrl, lastUrl].filter(Boolean);
  882. if (!referenceUrls.length) return;
  883. const tabs = await chrome.tabs.query({});
  884. const matchedIds = tabs
  885. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  886. .filter((tab) => referenceUrls.some((refUrl) => matchesSourceUrlFamily(source, tab.url, refUrl)))
  887. .map(tab => tab.id);
  888. if (!matchedIds.length) return;
  889. await chrome.tabs.remove(matchedIds).catch(() => { });
  890. const registry = await getTabRegistry();
  891. if (registry[source]?.tabId && matchedIds.includes(registry[source].tabId)) {
  892. registry[source] = null;
  893. await setState({ tabRegistry: registry });
  894. }
  895. await addLog(`已关闭 ${matchedIds.length} 个旧的${getSourceLabel(source)}标签页。`, 'info');
  896. }
  897. function isLocalhostOAuthCallbackTabMatch(callbackUrl, candidateUrl) {
  898. if (!isLocalhostOAuthCallbackUrl(callbackUrl) || !isLocalhostOAuthCallbackUrl(candidateUrl)) {
  899. return false;
  900. }
  901. const callback = parseUrlSafely(callbackUrl);
  902. const candidate = parseUrlSafely(candidateUrl);
  903. if (!callback || !candidate) return false;
  904. return callback.origin === candidate.origin
  905. && callback.pathname === candidate.pathname
  906. && callback.searchParams.get('code') === candidate.searchParams.get('code')
  907. && callback.searchParams.get('state') === candidate.searchParams.get('state');
  908. }
  909. async function closeLocalhostCallbackTabs(callbackUrl, options = {}) {
  910. if (!isLocalhostOAuthCallbackUrl(callbackUrl)) return 0;
  911. const { excludeTabIds = [] } = options;
  912. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  913. const tabs = await chrome.tabs.query({});
  914. const matchedIds = tabs
  915. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  916. .filter((tab) => isLocalhostOAuthCallbackTabMatch(callbackUrl, tab.url))
  917. .map((tab) => tab.id);
  918. if (!matchedIds.length) return 0;
  919. await chrome.tabs.remove(matchedIds).catch(() => { });
  920. const registry = await getTabRegistry();
  921. if (registry['signup-page']?.tabId && matchedIds.includes(registry['signup-page'].tabId)) {
  922. registry['signup-page'] = null;
  923. await setState({ tabRegistry: registry });
  924. }
  925. await addLog(`已关闭 ${matchedIds.length} 个匹配当前 OAuth callback 的 localhost 残留标签页。`, 'info');
  926. return matchedIds.length;
  927. }
  928. async function pingContentScriptOnTab(tabId) {
  929. if (!Number.isInteger(tabId)) return null;
  930. try {
  931. return await chrome.tabs.sendMessage(tabId, {
  932. type: 'PING',
  933. source: 'background',
  934. payload: {},
  935. });
  936. } catch {
  937. return null;
  938. }
  939. }
  940. async function waitForTabUrlFamily(source, tabId, referenceUrl, options = {}) {
  941. const { timeoutMs = 15000, retryDelayMs = 400 } = options;
  942. const start = Date.now();
  943. while (Date.now() - start < timeoutMs) {
  944. try {
  945. const tab = await chrome.tabs.get(tabId);
  946. if (matchesSourceUrlFamily(source, tab.url, referenceUrl)) {
  947. return tab;
  948. }
  949. } catch {
  950. return null;
  951. }
  952. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  953. }
  954. return null;
  955. }
  956. async function ensureContentScriptReadyOnTab(source, tabId, options = {}) {
  957. const {
  958. inject = null,
  959. injectSource = null,
  960. timeoutMs = 30000,
  961. retryDelayMs = 700,
  962. logMessage = '',
  963. } = options;
  964. const start = Date.now();
  965. let lastError = null;
  966. let logged = false;
  967. let attempt = 0;
  968. console.log(
  969. LOG_PREFIX,
  970. `[ensureContentScriptReadyOnTab] start ${source} tab=${tabId}, timeout=${timeoutMs}ms, inject=${Array.isArray(inject) ? inject.join(',') : 'none'}`
  971. );
  972. while (Date.now() - start < timeoutMs) {
  973. attempt += 1;
  974. const pong = await pingContentScriptOnTab(tabId);
  975. if (pong?.ok && (!pong.source || pong.source === source)) {
  976. console.log(
  977. LOG_PREFIX,
  978. `[ensureContentScriptReadyOnTab] ready ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  979. );
  980. await registerTab(source, tabId);
  981. return;
  982. }
  983. if (!inject || !inject.length) {
  984. throw new Error(`${getSourceLabel(source)} 内容脚本未就绪,且未提供可用的注入文件。`);
  985. }
  986. const registry = await getTabRegistry();
  987. if (registry[source]) {
  988. registry[source].ready = false;
  989. await setState({ tabRegistry: registry });
  990. }
  991. try {
  992. if (injectSource) {
  993. await chrome.scripting.executeScript({
  994. target: { tabId },
  995. func: (injectedSource) => {
  996. window.__MULTIPAGE_SOURCE = injectedSource;
  997. },
  998. args: [injectSource],
  999. });
  1000. }
  1001. await chrome.scripting.executeScript({
  1002. target: { tabId },
  1003. files: inject,
  1004. });
  1005. } catch (err) {
  1006. lastError = err;
  1007. console.warn(
  1008. LOG_PREFIX,
  1009. `[ensureContentScriptReadyOnTab] inject attempt ${attempt} failed for ${source} tab=${tabId}: ${err?.message || err}`
  1010. );
  1011. }
  1012. const pongAfterInject = await pingContentScriptOnTab(tabId);
  1013. if (pongAfterInject?.ok && (!pongAfterInject.source || pongAfterInject.source === source)) {
  1014. console.log(
  1015. LOG_PREFIX,
  1016. `[ensureContentScriptReadyOnTab] ready after inject ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  1017. );
  1018. await registerTab(source, tabId);
  1019. return;
  1020. }
  1021. if (logMessage && !logged) {
  1022. console.warn(
  1023. LOG_PREFIX,
  1024. `[ensureContentScriptReadyOnTab] ${source} tab=${tabId} still not ready after ${Date.now() - start}ms`
  1025. );
  1026. await addLog(logMessage, 'warn');
  1027. logged = true;
  1028. }
  1029. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  1030. }
  1031. throw lastError || new Error(`${getSourceLabel(source)} 内容脚本长时间未就绪。`);
  1032. }
  1033. // ============================================================
  1034. // Command Queue (for content scripts not yet ready)
  1035. // ============================================================
  1036. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  1037. function getContentScriptResponseTimeoutMs(message) {
  1038. if (!message || typeof message !== 'object') {
  1039. return 30000;
  1040. }
  1041. if (message.type === 'POLL_EMAIL') {
  1042. const maxAttempts = Math.max(1, Number(message.payload?.maxAttempts) || 1);
  1043. const intervalMs = Math.max(0, Number(message.payload?.intervalMs) || 0);
  1044. return Math.max(45000, maxAttempts * intervalMs + 25000);
  1045. }
  1046. if (message.type === 'FILL_CODE') {
  1047. return Number(message.step) === 7 ? 45000 : 30000;
  1048. }
  1049. if (message.type === 'PREPARE_SIGNUP_VERIFICATION') {
  1050. return 45000;
  1051. }
  1052. return 30000;
  1053. }
  1054. function getMessageDebugLabel(source, message, tabId = null) {
  1055. const parts = [source || 'unknown', message?.type || 'UNKNOWN'];
  1056. if (Number.isInteger(message?.step)) {
  1057. parts.push(`step=${message.step}`);
  1058. }
  1059. if (Number.isInteger(tabId)) {
  1060. parts.push(`tab=${tabId}`);
  1061. }
  1062. return parts.join(' ');
  1063. }
  1064. function summarizeMessageResultForDebug(result) {
  1065. if (result === undefined) return 'undefined';
  1066. if (result === null) return 'null';
  1067. if (typeof result !== 'object') return JSON.stringify(result);
  1068. const summary = {};
  1069. for (const key of ['ok', 'error', 'stopped', 'source', 'step']) {
  1070. if (key in result) summary[key] = result[key];
  1071. }
  1072. if (result.payload && typeof result.payload === 'object') {
  1073. summary.payloadKeys = Object.keys(result.payload);
  1074. }
  1075. return JSON.stringify(summary);
  1076. }
  1077. function sendTabMessageWithTimeout(tabId, source, message, responseTimeoutMs = getContentScriptResponseTimeoutMs(message)) {
  1078. return new Promise((resolve, reject) => {
  1079. let settled = false;
  1080. const startedAt = Date.now();
  1081. const debugLabel = getMessageDebugLabel(source, message, tabId);
  1082. console.log(LOG_PREFIX, `[sendTabMessageWithTimeout] dispatch ${debugLabel}, timeout=${responseTimeoutMs}ms`);
  1083. const timer = setTimeout(() => {
  1084. if (settled) return;
  1085. settled = true;
  1086. const seconds = Math.ceil(responseTimeoutMs / 1000);
  1087. console.warn(LOG_PREFIX, `[sendTabMessageWithTimeout] timeout ${debugLabel} after ${Date.now() - startedAt}ms`);
  1088. reject(new Error(`Content script on ${source} did not respond in ${seconds}s. Try refreshing the tab and retry.`));
  1089. }, responseTimeoutMs);
  1090. chrome.tabs.sendMessage(tabId, message)
  1091. .then((value) => {
  1092. const elapsed = Date.now() - startedAt;
  1093. if (settled) {
  1094. console.warn(
  1095. LOG_PREFIX,
  1096. `[sendTabMessageWithTimeout] late response ignored for ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  1097. );
  1098. return;
  1099. }
  1100. settled = true;
  1101. clearTimeout(timer);
  1102. console.log(
  1103. LOG_PREFIX,
  1104. `[sendTabMessageWithTimeout] response ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  1105. );
  1106. resolve(value);
  1107. })
  1108. .catch((error) => {
  1109. const elapsed = Date.now() - startedAt;
  1110. const errorMessage = error?.message || String(error);
  1111. if (settled) {
  1112. console.warn(
  1113. LOG_PREFIX,
  1114. `[sendTabMessageWithTimeout] late rejection ignored for ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  1115. );
  1116. return;
  1117. }
  1118. settled = true;
  1119. clearTimeout(timer);
  1120. console.warn(
  1121. LOG_PREFIX,
  1122. `[sendTabMessageWithTimeout] rejection ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  1123. );
  1124. reject(error);
  1125. });
  1126. });
  1127. }
  1128. function queueCommand(source, message, timeout = 15000) {
  1129. return new Promise((resolve, reject) => {
  1130. const timer = setTimeout(() => {
  1131. pendingCommands.delete(source);
  1132. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  1133. console.error(LOG_PREFIX, err);
  1134. reject(new Error(err));
  1135. }, timeout);
  1136. pendingCommands.set(source, { message, resolve, reject, timer });
  1137. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  1138. });
  1139. }
  1140. function flushCommand(source, tabId) {
  1141. const pending = pendingCommands.get(source);
  1142. if (pending) {
  1143. clearTimeout(pending.timer);
  1144. pendingCommands.delete(source);
  1145. sendTabMessageWithTimeout(tabId, source, pending.message).then(pending.resolve).catch(pending.reject);
  1146. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  1147. }
  1148. }
  1149. function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
  1150. for (const [source, pending] of pendingCommands.entries()) {
  1151. clearTimeout(pending.timer);
  1152. pending.reject(new Error(reason));
  1153. pendingCommands.delete(source);
  1154. console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
  1155. }
  1156. }
  1157. // ============================================================
  1158. // Reuse or create tab
  1159. // ============================================================
  1160. async function reuseOrCreateTab(source, url, options = {}) {
  1161. const alive = await isTabAlive(source);
  1162. if (alive) {
  1163. const tabId = await getTabId(source);
  1164. await closeConflictingTabsForSource(source, url, { excludeTabIds: [tabId] });
  1165. const currentTab = await chrome.tabs.get(tabId);
  1166. const sameUrl = currentTab.url === url;
  1167. const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
  1168. const registry = await getTabRegistry();
  1169. if (sameUrl) {
  1170. await chrome.tabs.update(tabId, { active: true });
  1171. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
  1172. if (shouldReloadOnReuse) {
  1173. if (registry[source]) registry[source].ready = false;
  1174. await setState({ tabRegistry: registry });
  1175. await chrome.tabs.reload(tabId);
  1176. await new Promise((resolve) => {
  1177. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  1178. const listener = (tid, info) => {
  1179. if (tid === tabId && info.status === 'complete') {
  1180. chrome.tabs.onUpdated.removeListener(listener);
  1181. clearTimeout(timer);
  1182. resolve();
  1183. }
  1184. };
  1185. chrome.tabs.onUpdated.addListener(listener);
  1186. });
  1187. }
  1188. // For dynamically injected pages like the VPS panel, re-inject immediately.
  1189. if (options.inject) {
  1190. if (registry[source]) registry[source].ready = false;
  1191. await setState({ tabRegistry: registry });
  1192. if (options.injectSource) {
  1193. await chrome.scripting.executeScript({
  1194. target: { tabId },
  1195. func: (injectedSource) => {
  1196. window.__MULTIPAGE_SOURCE = injectedSource;
  1197. },
  1198. args: [options.injectSource],
  1199. });
  1200. }
  1201. await chrome.scripting.executeScript({
  1202. target: { tabId },
  1203. files: options.inject,
  1204. });
  1205. await new Promise(r => setTimeout(r, 500));
  1206. }
  1207. await rememberSourceLastUrl(source, url);
  1208. return tabId;
  1209. }
  1210. // Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
  1211. if (registry[source]) registry[source].ready = false;
  1212. await setState({ tabRegistry: registry });
  1213. // Navigate existing tab to new URL
  1214. await chrome.tabs.update(tabId, { url, active: true });
  1215. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
  1216. // Wait for page load complete (with 30s timeout)
  1217. await new Promise((resolve) => {
  1218. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  1219. const listener = (tid, info) => {
  1220. if (tid === tabId && info.status === 'complete') {
  1221. chrome.tabs.onUpdated.removeListener(listener);
  1222. clearTimeout(timer);
  1223. resolve();
  1224. }
  1225. };
  1226. chrome.tabs.onUpdated.addListener(listener);
  1227. });
  1228. // If dynamic injection needed (VPS panel), re-inject after navigation
  1229. if (options.inject) {
  1230. if (options.injectSource) {
  1231. await chrome.scripting.executeScript({
  1232. target: { tabId },
  1233. func: (injectedSource) => {
  1234. window.__MULTIPAGE_SOURCE = injectedSource;
  1235. },
  1236. args: [options.injectSource],
  1237. });
  1238. }
  1239. await chrome.scripting.executeScript({
  1240. target: { tabId },
  1241. files: options.inject,
  1242. });
  1243. }
  1244. // Wait a bit for content script to inject and send READY
  1245. await new Promise(r => setTimeout(r, 500));
  1246. await rememberSourceLastUrl(source, url);
  1247. return tabId;
  1248. }
  1249. // Create new tab
  1250. await closeConflictingTabsForSource(source, url);
  1251. const tab = await chrome.tabs.create({ url, active: true });
  1252. console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
  1253. // If dynamic injection needed (VPS panel), inject scripts after load
  1254. if (options.inject) {
  1255. await new Promise((resolve) => {
  1256. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  1257. const listener = (tabId, info) => {
  1258. if (tabId === tab.id && info.status === 'complete') {
  1259. chrome.tabs.onUpdated.removeListener(listener);
  1260. clearTimeout(timer);
  1261. resolve();
  1262. }
  1263. };
  1264. chrome.tabs.onUpdated.addListener(listener);
  1265. });
  1266. if (options.injectSource) {
  1267. await chrome.scripting.executeScript({
  1268. target: { tabId: tab.id },
  1269. func: (injectedSource) => {
  1270. window.__MULTIPAGE_SOURCE = injectedSource;
  1271. },
  1272. args: [options.injectSource],
  1273. });
  1274. }
  1275. await chrome.scripting.executeScript({
  1276. target: { tabId: tab.id },
  1277. files: options.inject,
  1278. });
  1279. }
  1280. await rememberSourceLastUrl(source, url);
  1281. return tab.id;
  1282. }
  1283. // ============================================================
  1284. // Send command to content script (with readiness check)
  1285. // ============================================================
  1286. async function sendToContentScript(source, message, options = {}) {
  1287. const { responseTimeoutMs = getContentScriptResponseTimeoutMs(message) } = options;
  1288. const registry = await getTabRegistry();
  1289. const entry = registry[source];
  1290. if (!entry || !entry.ready) {
  1291. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  1292. return queueCommand(source, message);
  1293. }
  1294. // Verify tab is still alive
  1295. const alive = await isTabAlive(source);
  1296. if (!alive) {
  1297. // Tab was closed — queue the command, it will be sent when tab is reopened
  1298. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  1299. return queueCommand(source, message);
  1300. }
  1301. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  1302. return sendTabMessageWithTimeout(entry.tabId, source, message, responseTimeoutMs);
  1303. }
  1304. async function sendToContentScriptResilient(source, message, options = {}) {
  1305. const { timeoutMs = 30000, retryDelayMs = 600, logMessage = '' } = options;
  1306. const start = Date.now();
  1307. let lastError = null;
  1308. let logged = false;
  1309. let attempt = 0;
  1310. const debugLabel = getMessageDebugLabel(source, message);
  1311. console.log(
  1312. LOG_PREFIX,
  1313. `[sendToContentScriptResilient] start ${debugLabel}, totalTimeout=${timeoutMs}ms, retryDelay=${retryDelayMs}ms`
  1314. );
  1315. while (Date.now() - start < timeoutMs) {
  1316. throwIfStopped();
  1317. attempt += 1;
  1318. try {
  1319. console.log(
  1320. LOG_PREFIX,
  1321. `[sendToContentScriptResilient] attempt ${attempt} -> ${debugLabel}, elapsed=${Date.now() - start}ms`
  1322. );
  1323. const result = await sendToContentScript(source, message);
  1324. console.log(
  1325. LOG_PREFIX,
  1326. `[sendToContentScriptResilient] success ${debugLabel} on attempt ${attempt} after ${Date.now() - start}ms`
  1327. );
  1328. return result;
  1329. } catch (err) {
  1330. const retryable = isRetryableContentScriptTransportError(err);
  1331. console.warn(
  1332. LOG_PREFIX,
  1333. `[sendToContentScriptResilient] attempt ${attempt} failed for ${debugLabel}, retryable=${retryable}, elapsed=${Date.now() - start}ms: ${err?.message || err}`
  1334. );
  1335. if (!retryable) {
  1336. throw err;
  1337. }
  1338. lastError = err;
  1339. if (logMessage && !logged) {
  1340. await addLog(logMessage, 'warn');
  1341. logged = true;
  1342. }
  1343. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  1344. }
  1345. }
  1346. throw lastError || new Error(`等待 ${getSourceLabel(source)} 重新就绪超时。`);
  1347. }
  1348. async function sendToMailContentScriptResilient(mail, message, options = {}) {
  1349. const { timeoutMs = 45000, maxRecoveryAttempts = 2 } = options;
  1350. const start = Date.now();
  1351. let lastError = null;
  1352. let recoveries = 0;
  1353. let logged = false;
  1354. while (Date.now() - start < timeoutMs) {
  1355. throwIfStopped();
  1356. try {
  1357. return await sendToContentScript(mail.source, message);
  1358. } catch (err) {
  1359. if (!isRetryableContentScriptTransportError(err)) {
  1360. throw err;
  1361. }
  1362. lastError = err;
  1363. if (!logged) {
  1364. await addLog(`步骤 ${message.step}:${mail.label} 页面通信异常,正在尝试让邮箱页重新就绪...`, 'warn');
  1365. logged = true;
  1366. }
  1367. if (recoveries >= maxRecoveryAttempts) {
  1368. break;
  1369. }
  1370. recoveries += 1;
  1371. await reuseOrCreateTab(mail.source, mail.url, {
  1372. inject: mail.inject,
  1373. injectSource: mail.injectSource,
  1374. reloadIfSameUrl: true,
  1375. });
  1376. await new Promise((resolve) => setTimeout(resolve, 800));
  1377. }
  1378. }
  1379. throw lastError || new Error(`${mail.label} 页面未能重新就绪。`);
  1380. }
  1381. // ============================================================
  1382. // Logging
  1383. // ============================================================
  1384. async function addLog(message, level = 'info') {
  1385. const state = await getState();
  1386. const logs = state.logs || [];
  1387. const entry = { message, level, timestamp: Date.now() };
  1388. logs.push(entry);
  1389. // Keep last 500 logs
  1390. if (logs.length > 500) logs.splice(0, logs.length - 500);
  1391. await setState({ logs });
  1392. // Broadcast to side panel
  1393. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => { });
  1394. }
  1395. function getStep8CallbackUrlFromNavigation(details, signupTabId) {
  1396. if (!Number.isInteger(signupTabId) || !details) return '';
  1397. if (details.tabId !== signupTabId) return '';
  1398. if (details.frameId !== 0) return '';
  1399. return isLocalhostOAuthCallbackUrl(details.url) ? details.url : '';
  1400. }
  1401. function getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId) {
  1402. if (!Number.isInteger(signupTabId) || tabId !== signupTabId) return '';
  1403. const candidates = [changeInfo?.url, tab?.url];
  1404. for (const candidate of candidates) {
  1405. if (isLocalhostOAuthCallbackUrl(candidate)) {
  1406. return candidate;
  1407. }
  1408. }
  1409. return '';
  1410. }
  1411. function getSourceLabel(source) {
  1412. const labels = {
  1413. 'sidepanel': '侧边栏',
  1414. 'signup-page': '认证页',
  1415. 'vps-panel': 'CPA 面板',
  1416. 'qq-mail': 'QQ 邮箱',
  1417. 'mail-163': '163 邮箱',
  1418. 'inbucket-mail': 'Inbucket 邮箱',
  1419. 'duck-mail': 'Duck 邮箱',
  1420. 'hotmail-api': 'Hotmail(微软 Graph)',
  1421. };
  1422. return labels[source] || source || '未知来源';
  1423. }
  1424. // ============================================================
  1425. // Step Status Management
  1426. // ============================================================
  1427. async function setStepStatus(step, status) {
  1428. const state = await getState();
  1429. const statuses = { ...state.stepStatuses };
  1430. statuses[step] = status;
  1431. await setState({ stepStatuses: statuses, currentStep: step });
  1432. // Broadcast to side panel
  1433. chrome.runtime.sendMessage({
  1434. type: 'STEP_STATUS_CHANGED',
  1435. payload: { step, status },
  1436. }).catch(() => { });
  1437. }
  1438. function isStopError(error) {
  1439. const message = typeof error === 'string' ? error : error?.message;
  1440. return message === STOP_ERROR_MESSAGE;
  1441. }
  1442. function isRetryableContentScriptTransportError(error) {
  1443. const message = String(typeof error === 'string' ? error : error?.message || '');
  1444. 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);
  1445. }
  1446. function getErrorMessage(error) {
  1447. return String(typeof error === 'string' ? error : error?.message || '');
  1448. }
  1449. function isVerificationMailPollingError(error) {
  1450. const message = getErrorMessage(error);
  1451. return /未在 .*邮箱中找到新的匹配邮件|未在 Hotmail 收件箱中找到新的匹配验证码|邮箱轮询结束,但未获取到验证码|无法获取新的(?:注册|登录)验证码|页面未能重新就绪|页面通信异常|did not respond in \d+s/i.test(message);
  1452. }
  1453. const STEP7_RESTART_FROM_STEP6_ERROR_CODE = 'STEP7_RESTART_FROM_STEP6';
  1454. const STEP7_RESTART_FROM_STEP6_MARKER_PATTERN = /^STEP7_RESTART_FROM_STEP6::([^:]+)::(.*)$/;
  1455. function createStep7RestartFromStep6Error(details = {}) {
  1456. const { reason = 'unknown', url = '' } = details || {};
  1457. const reasonLabel = reason === 'login_timeout_error_page'
  1458. ? '检测到登录页超时报错'
  1459. : '步骤 7 请求回到步骤 6';
  1460. const error = new Error(`步骤 7:${reasonLabel}。${url ? `URL: ${url}` : ''}`.trim());
  1461. error.code = STEP7_RESTART_FROM_STEP6_ERROR_CODE;
  1462. error.restartReason = reason;
  1463. error.restartUrl = url;
  1464. return error;
  1465. }
  1466. function parseStep7RestartFromStep6Marker(message) {
  1467. const normalized = getErrorMessage(message);
  1468. const match = normalized.match(STEP7_RESTART_FROM_STEP6_MARKER_PATTERN);
  1469. if (!match) {
  1470. return null;
  1471. }
  1472. return {
  1473. reason: match[1] || 'unknown',
  1474. url: match[2] || '',
  1475. };
  1476. }
  1477. function getStep7RestartFromStep6Error(result) {
  1478. if (result?.restartFromStep6) {
  1479. return createStep7RestartFromStep6Error(result);
  1480. }
  1481. const parsed = parseStep7RestartFromStep6Marker(result?.error);
  1482. if (!parsed) {
  1483. return null;
  1484. }
  1485. return createStep7RestartFromStep6Error(parsed);
  1486. }
  1487. function isStep7RestartFromStep6Error(error) {
  1488. return error?.code === STEP7_RESTART_FROM_STEP6_ERROR_CODE
  1489. || Boolean(parseStep7RestartFromStep6Marker(error));
  1490. }
  1491. function isStep7RecoverableError(error) {
  1492. return isVerificationMailPollingError(error) || isStep7RestartFromStep6Error(error);
  1493. }
  1494. function isRestartCurrentAttemptError(error) {
  1495. const message = String(typeof error === 'string' ? error : error?.message || '');
  1496. return /当前邮箱已存在,需要重新开始新一轮/.test(message);
  1497. }
  1498. function isStep9RecoverableAuthError(error) {
  1499. const message = String(typeof error === 'string' ? error : error?.message || '');
  1500. return /STEP9_OAUTH_RETRY::/i.test(message)
  1501. || isRecoverableStep9AuthFailure(message);
  1502. }
  1503. function isLegacyStep9RecoverableAuthError(error) {
  1504. const message = String(typeof error === 'string' ? error : error?.message || '');
  1505. return /STEP9_OAUTH_TIMEOUT::|认证失败:\s*Timeout waiting for OAuth callback/i.test(message);
  1506. }
  1507. function isStepDoneStatus(status) {
  1508. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  1509. }
  1510. function getFirstUnfinishedStep(statuses = {}) {
  1511. for (let step = 1; step <= 9; step++) {
  1512. if (!isStepDoneStatus(statuses[step] || 'pending')) {
  1513. return step;
  1514. }
  1515. }
  1516. return null;
  1517. }
  1518. function hasSavedProgress(statuses = {}) {
  1519. return Object.values({ ...DEFAULT_STATE.stepStatuses, ...statuses }).some((status) => status !== 'pending');
  1520. }
  1521. function getDownstreamStateResets(step) {
  1522. if (step <= 1) {
  1523. return {
  1524. oauthUrl: null,
  1525. flowStartTime: null,
  1526. password: null,
  1527. lastEmailTimestamp: null,
  1528. signupVerificationRequestedAt: null,
  1529. loginVerificationRequestedAt: null,
  1530. lastSignupCode: null,
  1531. lastLoginCode: null,
  1532. localhostUrl: null,
  1533. };
  1534. }
  1535. if (step === 2) {
  1536. return {
  1537. password: null,
  1538. lastEmailTimestamp: null,
  1539. signupVerificationRequestedAt: null,
  1540. loginVerificationRequestedAt: null,
  1541. lastSignupCode: null,
  1542. lastLoginCode: null,
  1543. localhostUrl: null,
  1544. };
  1545. }
  1546. if (step === 3 || step === 4) {
  1547. return {
  1548. lastEmailTimestamp: null,
  1549. signupVerificationRequestedAt: null,
  1550. loginVerificationRequestedAt: null,
  1551. lastSignupCode: null,
  1552. lastLoginCode: null,
  1553. localhostUrl: null,
  1554. };
  1555. }
  1556. if (step === 5 || step === 6 || step === 7) {
  1557. return {
  1558. lastLoginCode: null,
  1559. loginVerificationRequestedAt: null,
  1560. localhostUrl: null,
  1561. };
  1562. }
  1563. if (step === 8) {
  1564. return {
  1565. localhostUrl: null,
  1566. };
  1567. }
  1568. return {};
  1569. }
  1570. async function invalidateDownstreamAfterStepRestart(step, options = {}) {
  1571. const { logLabel = `步骤 ${step} 重新执行` } = options;
  1572. const state = await getState();
  1573. const statuses = { ...(state.stepStatuses || {}) };
  1574. const changedSteps = [];
  1575. for (let downstream = step + 1; downstream <= 9; downstream++) {
  1576. if (statuses[downstream] !== 'pending') {
  1577. statuses[downstream] = 'pending';
  1578. changedSteps.push(downstream);
  1579. }
  1580. }
  1581. if (changedSteps.length) {
  1582. await setState({ stepStatuses: statuses });
  1583. for (const downstream of changedSteps) {
  1584. chrome.runtime.sendMessage({
  1585. type: 'STEP_STATUS_CHANGED',
  1586. payload: { step: downstream, status: 'pending' },
  1587. }).catch(() => { });
  1588. }
  1589. await addLog(`${logLabel},已重置后续步骤状态:${changedSteps.join(', ')}`, 'warn');
  1590. }
  1591. const resets = getDownstreamStateResets(step);
  1592. if (Object.keys(resets).length) {
  1593. await setState(resets);
  1594. broadcastDataUpdate(resets);
  1595. }
  1596. }
  1597. function clearStopRequest() {
  1598. stopRequested = false;
  1599. }
  1600. function getAutoRunStatusPayload(phase, payload = {}) {
  1601. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  1602. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  1603. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  1604. const rawScheduledAt = phase === 'scheduled'
  1605. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  1606. : null;
  1607. const scheduledAt = rawScheduledAt === null ? null : Number(rawScheduledAt);
  1608. const autoRunning = phase === 'scheduled' || phase === 'running' || phase === 'waiting_email' || phase === 'retrying';
  1609. return {
  1610. autoRunning,
  1611. autoRunPhase: phase,
  1612. autoRunCurrentRun: currentRun,
  1613. autoRunTotalRuns: totalRuns,
  1614. autoRunAttemptRun: attemptRun,
  1615. scheduledAutoRunAt: Number.isFinite(scheduledAt) ? scheduledAt : null,
  1616. };
  1617. }
  1618. async function broadcastAutoRunStatus(phase, payload = {}, extraState = {}) {
  1619. const rawScheduledAt = phase === 'scheduled'
  1620. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  1621. : null;
  1622. const statusPayload = {
  1623. phase,
  1624. currentRun: payload.currentRun ?? autoRunCurrentRun,
  1625. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  1626. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  1627. scheduledAt: rawScheduledAt === null ? null : Number(rawScheduledAt),
  1628. };
  1629. await setState({
  1630. ...extraState,
  1631. ...getAutoRunStatusPayload(phase, statusPayload),
  1632. });
  1633. chrome.runtime.sendMessage({
  1634. type: 'AUTO_RUN_STATUS',
  1635. payload: statusPayload,
  1636. }).catch(() => { });
  1637. }
  1638. function isAutoRunLockedState(state) {
  1639. return Boolean(state.autoRunning) && (state.autoRunPhase === 'running' || state.autoRunPhase === 'retrying');
  1640. }
  1641. function isAutoRunPausedState(state) {
  1642. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  1643. }
  1644. function isAutoRunScheduledState(state) {
  1645. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  1646. return Boolean(state.autoRunning)
  1647. && state.autoRunPhase === 'scheduled'
  1648. && Number.isFinite(scheduledAt)
  1649. && Boolean(normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan));
  1650. }
  1651. function formatAutoRunScheduleTime(timestamp) {
  1652. return new Date(timestamp).toLocaleString('zh-CN', {
  1653. hour12: false,
  1654. month: '2-digit',
  1655. day: '2-digit',
  1656. hour: '2-digit',
  1657. minute: '2-digit',
  1658. second: '2-digit',
  1659. });
  1660. }
  1661. async function setAutoRunDelayEnabledState(enabled) {
  1662. const normalized = Boolean(enabled);
  1663. await setPersistentSettings({ autoRunDelayEnabled: normalized });
  1664. await setState({ autoRunDelayEnabled: normalized });
  1665. broadcastDataUpdate({ autoRunDelayEnabled: normalized });
  1666. }
  1667. async function ensureScheduledAutoRunAlarm(scheduledAt) {
  1668. if (!Number.isFinite(scheduledAt) || scheduledAt <= Date.now()) {
  1669. return false;
  1670. }
  1671. const existingAlarm = await chrome.alarms.get(AUTO_RUN_ALARM_NAME);
  1672. if (!existingAlarm || Math.abs((existingAlarm.scheduledTime || 0) - scheduledAt) > 1000) {
  1673. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  1674. await chrome.alarms.create(AUTO_RUN_ALARM_NAME, { when: scheduledAt });
  1675. }
  1676. return true;
  1677. }
  1678. async function clearScheduledAutoRunAlarm() {
  1679. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  1680. }
  1681. async function scheduleAutoRun(totalRuns, options = {}) {
  1682. const state = await getState();
  1683. if (isAutoRunLockedState(state) || isAutoRunPausedState(state) || autoRunActive) {
  1684. throw new Error('自动运行已在进行中,请先停止后再重新计划。');
  1685. }
  1686. if (isAutoRunScheduledState(state)) {
  1687. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  1688. }
  1689. const delayMinutes = normalizeAutoRunDelayMinutes(options.delayMinutes);
  1690. const plan = normalizeScheduledAutoRunPlan({
  1691. totalRuns,
  1692. autoRunSkipFailures: options.autoRunSkipFailures,
  1693. mode: options.mode,
  1694. });
  1695. const scheduledAt = Date.now() + delayMinutes * 60 * 1000;
  1696. autoRunCurrentRun = 0;
  1697. autoRunTotalRuns = plan.totalRuns;
  1698. autoRunAttemptRun = 0;
  1699. await ensureScheduledAutoRunAlarm(scheduledAt);
  1700. await broadcastAutoRunStatus(
  1701. 'scheduled',
  1702. {
  1703. currentRun: 0,
  1704. totalRuns: plan.totalRuns,
  1705. attemptRun: 0,
  1706. scheduledAt,
  1707. },
  1708. {
  1709. autoRunSkipFailures: plan.autoRunSkipFailures,
  1710. scheduledAutoRunPlan: plan,
  1711. }
  1712. );
  1713. await addLog(
  1714. `自动运行已计划:${delayMinutes} 分钟后启动(${formatAutoRunScheduleTime(scheduledAt)}),目标 ${plan.totalRuns} 轮。`,
  1715. 'info'
  1716. );
  1717. return { ok: true, scheduledAt };
  1718. }
  1719. let scheduledAutoRunLaunching = false;
  1720. async function launchScheduledAutoRun(trigger = 'alarm') {
  1721. if (scheduledAutoRunLaunching) {
  1722. return false;
  1723. }
  1724. scheduledAutoRunLaunching = true;
  1725. try {
  1726. const state = await getState();
  1727. if (!isAutoRunScheduledState(state)) {
  1728. return false;
  1729. }
  1730. if (autoRunActive) {
  1731. return false;
  1732. }
  1733. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1734. if (!plan) {
  1735. await clearScheduledAutoRunAlarm();
  1736. await broadcastAutoRunStatus('idle', {
  1737. currentRun: 0,
  1738. totalRuns: 1,
  1739. attemptRun: 0,
  1740. }, {
  1741. scheduledAutoRunPlan: null,
  1742. });
  1743. return false;
  1744. }
  1745. await clearScheduledAutoRunAlarm();
  1746. if (trigger !== 'manual' && state.autoRunDelayEnabled) {
  1747. await setAutoRunDelayEnabledState(false);
  1748. }
  1749. await broadcastAutoRunStatus(
  1750. 'running',
  1751. {
  1752. currentRun: 0,
  1753. totalRuns: plan.totalRuns,
  1754. attemptRun: 0,
  1755. },
  1756. {
  1757. autoRunSkipFailures: plan.autoRunSkipFailures,
  1758. scheduledAutoRunPlan: null,
  1759. }
  1760. );
  1761. clearStopRequest();
  1762. await addLog(
  1763. trigger === 'manual'
  1764. ? '已手动跳过倒计时,自动运行立即开始。'
  1765. : '倒计时结束,自动运行开始执行。',
  1766. 'info'
  1767. );
  1768. autoRunLoop(plan.totalRuns, {
  1769. autoRunSkipFailures: plan.autoRunSkipFailures,
  1770. mode: plan.mode,
  1771. });
  1772. return true;
  1773. } finally {
  1774. scheduledAutoRunLaunching = false;
  1775. }
  1776. }
  1777. async function cancelScheduledAutoRun(options = {}) {
  1778. const state = await getState();
  1779. if (!isAutoRunScheduledState(state)) {
  1780. return false;
  1781. }
  1782. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1783. await clearScheduledAutoRunAlarm();
  1784. autoRunCurrentRun = 0;
  1785. autoRunTotalRuns = plan?.totalRuns || 1;
  1786. autoRunAttemptRun = 0;
  1787. await broadcastAutoRunStatus(
  1788. 'idle',
  1789. {
  1790. currentRun: 0,
  1791. totalRuns: plan?.totalRuns || 1,
  1792. attemptRun: 0,
  1793. },
  1794. {
  1795. scheduledAutoRunPlan: null,
  1796. }
  1797. );
  1798. if (options.logMessage !== false) {
  1799. await addLog(options.logMessage || '已取消自动运行倒计时计划。', 'warn');
  1800. }
  1801. return true;
  1802. }
  1803. async function restoreScheduledAutoRunIfNeeded() {
  1804. const state = await getState();
  1805. if (state.autoRunPhase !== 'scheduled') {
  1806. return;
  1807. }
  1808. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1809. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  1810. if (!plan || !Number.isFinite(scheduledAt)) {
  1811. await clearScheduledAutoRunAlarm();
  1812. await broadcastAutoRunStatus('idle', {
  1813. currentRun: 0,
  1814. totalRuns: 1,
  1815. attemptRun: 0,
  1816. }, {
  1817. scheduledAutoRunPlan: null,
  1818. });
  1819. return;
  1820. }
  1821. if (scheduledAt <= Date.now()) {
  1822. await launchScheduledAutoRun('restore');
  1823. return;
  1824. }
  1825. await ensureScheduledAutoRunAlarm(scheduledAt);
  1826. }
  1827. async function ensureManualInteractionAllowed(actionLabel) {
  1828. const state = await getState();
  1829. if (isAutoRunLockedState(state)) {
  1830. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  1831. }
  1832. if (isAutoRunPausedState(state)) {
  1833. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  1834. }
  1835. if (isAutoRunScheduledState(state)) {
  1836. throw new Error(`自动流程已计划启动。请先取消计划,或立即开始后再${actionLabel}。`);
  1837. }
  1838. return state;
  1839. }
  1840. async function skipStep(step) {
  1841. const state = await ensureManualInteractionAllowed('跳过步骤');
  1842. if (!Number.isInteger(step) || step < 1 || step > 9) {
  1843. throw new Error(`无效步骤:${step}`);
  1844. }
  1845. const statuses = { ...(state.stepStatuses || {}) };
  1846. const currentStatus = statuses[step];
  1847. if (currentStatus === 'running') {
  1848. throw new Error(`步骤 ${step} 正在运行中,不能跳过。`);
  1849. }
  1850. if (isStepDoneStatus(currentStatus)) {
  1851. throw new Error(`步骤 ${step} 已完成,无需再跳过。`);
  1852. }
  1853. if (step > 1) {
  1854. const prevStatus = statuses[step - 1];
  1855. if (!isStepDoneStatus(prevStatus)) {
  1856. throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`);
  1857. }
  1858. }
  1859. await setStepStatus(step, 'skipped');
  1860. await addLog(`步骤 ${step} 已跳过`, 'warn');
  1861. if (step === 1) {
  1862. const latestState = await getState();
  1863. const step2Status = latestState.stepStatuses?.[2];
  1864. if (!isStepDoneStatus(step2Status) && step2Status !== 'running') {
  1865. await setStepStatus(2, 'skipped');
  1866. await addLog('步骤 1 已跳过,步骤 2 也已同时跳过。', 'warn');
  1867. }
  1868. }
  1869. return { ok: true, step, status: 'skipped' };
  1870. }
  1871. function throwIfStopped() {
  1872. if (stopRequested) {
  1873. throw new Error(STOP_ERROR_MESSAGE);
  1874. }
  1875. }
  1876. async function sleepWithStop(ms) {
  1877. const start = Date.now();
  1878. while (Date.now() - start < ms) {
  1879. throwIfStopped();
  1880. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  1881. }
  1882. }
  1883. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  1884. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  1885. await sleepWithStop(duration);
  1886. }
  1887. async function clickWithDebugger(tabId, rect) {
  1888. if (!tabId) {
  1889. throw new Error('未找到用于调试点击的认证页面标签页。');
  1890. }
  1891. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  1892. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  1893. }
  1894. const target = { tabId };
  1895. try {
  1896. await chrome.debugger.attach(target, '1.3');
  1897. } catch (err) {
  1898. throw new Error(
  1899. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  1900. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  1901. );
  1902. }
  1903. try {
  1904. const x = Math.round(rect.centerX);
  1905. const y = Math.round(rect.centerY);
  1906. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  1907. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1908. type: 'mouseMoved',
  1909. x,
  1910. y,
  1911. button: 'none',
  1912. buttons: 0,
  1913. clickCount: 0,
  1914. });
  1915. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1916. type: 'mousePressed',
  1917. x,
  1918. y,
  1919. button: 'left',
  1920. buttons: 1,
  1921. clickCount: 1,
  1922. });
  1923. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1924. type: 'mouseReleased',
  1925. x,
  1926. y,
  1927. button: 'left',
  1928. buttons: 0,
  1929. clickCount: 1,
  1930. });
  1931. } finally {
  1932. await chrome.debugger.detach(target).catch(() => { });
  1933. }
  1934. }
  1935. async function broadcastStopToContentScripts() {
  1936. const registry = await getTabRegistry();
  1937. for (const entry of Object.values(registry)) {
  1938. if (!entry?.tabId) continue;
  1939. try {
  1940. await chrome.tabs.sendMessage(entry.tabId, {
  1941. type: 'STOP_FLOW',
  1942. source: 'background',
  1943. payload: {},
  1944. });
  1945. } catch { }
  1946. }
  1947. }
  1948. let stopRequested = false;
  1949. // ============================================================
  1950. // Message Handler (central router)
  1951. // ============================================================
  1952. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  1953. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  1954. handleMessage(message, sender).then(response => {
  1955. sendResponse(response);
  1956. }).catch(err => {
  1957. console.error(LOG_PREFIX, 'Handler error:', err);
  1958. sendResponse({ error: err.message });
  1959. });
  1960. return true; // async response
  1961. });
  1962. async function handleMessage(message, sender) {
  1963. switch (message.type) {
  1964. case 'CONTENT_SCRIPT_READY': {
  1965. const tabId = sender.tab?.id;
  1966. if (tabId && message.source) {
  1967. await registerTab(message.source, tabId);
  1968. flushCommand(message.source, tabId);
  1969. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  1970. }
  1971. return { ok: true };
  1972. }
  1973. case 'LOG': {
  1974. const { message: msg, level } = message.payload;
  1975. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  1976. return { ok: true };
  1977. }
  1978. case 'STEP_COMPLETE': {
  1979. if (stopRequested) {
  1980. await setStepStatus(message.step, 'stopped');
  1981. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  1982. return { ok: true };
  1983. }
  1984. await setStepStatus(message.step, 'completed');
  1985. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  1986. await handleStepData(message.step, message.payload);
  1987. notifyStepComplete(message.step, message.payload);
  1988. return { ok: true };
  1989. }
  1990. case 'STEP_ERROR': {
  1991. if (isStopError(message.error)) {
  1992. await setStepStatus(message.step, 'stopped');
  1993. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  1994. notifyStepError(message.step, message.error);
  1995. } else {
  1996. await setStepStatus(message.step, 'failed');
  1997. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  1998. notifyStepError(message.step, message.error);
  1999. }
  2000. return { ok: true };
  2001. }
  2002. case 'GET_STATE': {
  2003. return await getState();
  2004. }
  2005. case 'RESET': {
  2006. clearStopRequest();
  2007. await clearScheduledAutoRunAlarm();
  2008. await resetState();
  2009. await addLog('流程已重置', 'info');
  2010. return { ok: true };
  2011. }
  2012. case 'EXECUTE_STEP': {
  2013. clearStopRequest();
  2014. if (message.source === 'sidepanel') {
  2015. await ensureManualInteractionAllowed('手动执行步骤');
  2016. }
  2017. const step = message.payload.step;
  2018. if (message.source === 'sidepanel') {
  2019. await invalidateDownstreamAfterStepRestart(step, { logLabel: `步骤 ${step} 重新执行` });
  2020. }
  2021. // Save email if provided (from side panel step 3)
  2022. if (message.payload.email) {
  2023. await setEmailState(message.payload.email);
  2024. }
  2025. await executeStep(step);
  2026. return { ok: true };
  2027. }
  2028. case 'AUTO_RUN': {
  2029. clearStopRequest();
  2030. const state = await getState();
  2031. if (isAutoRunScheduledState(state)) {
  2032. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  2033. }
  2034. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  2035. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  2036. const mode = message.payload?.mode === 'continue' ? 'continue' : 'restart';
  2037. await setState({ autoRunSkipFailures });
  2038. autoRunLoop(totalRuns, { autoRunSkipFailures, mode }); // fire-and-forget
  2039. return { ok: true };
  2040. }
  2041. case 'SCHEDULE_AUTO_RUN': {
  2042. clearStopRequest();
  2043. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  2044. return await scheduleAutoRun(totalRuns, {
  2045. delayMinutes: message.payload?.delayMinutes,
  2046. autoRunSkipFailures: Boolean(message.payload?.autoRunSkipFailures),
  2047. mode: message.payload?.mode,
  2048. });
  2049. }
  2050. case 'START_SCHEDULED_AUTO_RUN_NOW': {
  2051. clearStopRequest();
  2052. const started = await launchScheduledAutoRun('manual');
  2053. if (!started) {
  2054. throw new Error('当前没有可立即开始的倒计时计划。');
  2055. }
  2056. return { ok: true };
  2057. }
  2058. case 'CANCEL_SCHEDULED_AUTO_RUN': {
  2059. const cancelled = await cancelScheduledAutoRun();
  2060. if (!cancelled) {
  2061. throw new Error('当前没有可取消的倒计时计划。');
  2062. }
  2063. return { ok: true };
  2064. }
  2065. case 'RESUME_AUTO_RUN': {
  2066. clearStopRequest();
  2067. if (message.payload.email) {
  2068. await setEmailState(message.payload.email);
  2069. }
  2070. resumeAutoRun(); // fire-and-forget
  2071. return { ok: true };
  2072. }
  2073. case 'TAKEOVER_AUTO_RUN': {
  2074. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  2075. await addLog('自动流程已切换为手动控制。', 'warn');
  2076. return { ok: true };
  2077. }
  2078. case 'SKIP_STEP': {
  2079. const step = Number(message.payload?.step);
  2080. return await skipStep(step);
  2081. }
  2082. case 'SAVE_SETTING': {
  2083. const updates = {};
  2084. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  2085. if (message.payload.vpsPassword !== undefined) updates.vpsPassword = message.payload.vpsPassword;
  2086. if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
  2087. if (message.payload.autoRunSkipFailures !== undefined) updates.autoRunSkipFailures = Boolean(message.payload.autoRunSkipFailures);
  2088. if (message.payload.autoRunDelayEnabled !== undefined) updates.autoRunDelayEnabled = Boolean(message.payload.autoRunDelayEnabled);
  2089. if (message.payload.autoRunDelayMinutes !== undefined) updates.autoRunDelayMinutes = normalizeAutoRunDelayMinutes(message.payload.autoRunDelayMinutes);
  2090. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  2091. if (message.payload.emailGenerator !== undefined) updates.emailGenerator = normalizeEmailGenerator(message.payload.emailGenerator);
  2092. if (message.payload.inbucketHost !== undefined) updates.inbucketHost = message.payload.inbucketHost;
  2093. if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
  2094. if (message.payload.cloudflareDomain !== undefined) updates.cloudflareDomain = normalizeCloudflareDomain(message.payload.cloudflareDomain);
  2095. if (message.payload.cloudflareDomains !== undefined) updates.cloudflareDomains = Array.isArray(message.payload.cloudflareDomains)
  2096. ? message.payload.cloudflareDomains.map(domain => normalizeCloudflareDomain(domain)).filter(Boolean)
  2097. : [];
  2098. await setPersistentSettings(updates);
  2099. await setState(updates);
  2100. return { ok: true };
  2101. }
  2102. case 'UPSERT_HOTMAIL_ACCOUNT': {
  2103. const account = await upsertHotmailAccount(message.payload || {});
  2104. return { ok: true, account };
  2105. }
  2106. case 'DELETE_HOTMAIL_ACCOUNT': {
  2107. await deleteHotmailAccount(String(message.payload?.accountId || ''));
  2108. return { ok: true };
  2109. }
  2110. case 'DELETE_HOTMAIL_ACCOUNTS': {
  2111. const result = await deleteHotmailAccounts(String(message.payload?.mode || 'all'));
  2112. return { ok: true, ...result };
  2113. }
  2114. case 'SELECT_HOTMAIL_ACCOUNT': {
  2115. const account = await setCurrentHotmailAccount(String(message.payload?.accountId || ''), {
  2116. markUsed: false,
  2117. syncEmail: true,
  2118. });
  2119. return { ok: true, account };
  2120. }
  2121. case 'PATCH_HOTMAIL_ACCOUNT': {
  2122. const account = await patchHotmailAccount(
  2123. String(message.payload?.accountId || ''),
  2124. message.payload?.updates || {}
  2125. );
  2126. return { ok: true, account };
  2127. }
  2128. case 'VERIFY_HOTMAIL_ACCOUNT':
  2129. case 'AUTHORIZE_HOTMAIL_ACCOUNT': {
  2130. const accountId = String(message.payload?.accountId || '');
  2131. try {
  2132. const result = await verifyHotmailAccount(accountId);
  2133. await setCurrentHotmailAccount(result.account.id, { markUsed: false, syncEmail: true });
  2134. await addLog(`Hotmail 账号 ${result.account.email} 校验通过,可直接用于收信。`, 'ok');
  2135. return { ok: true, account: result.account, messageCount: result.messageCount };
  2136. } catch (err) {
  2137. const state = await getState();
  2138. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  2139. const target = findHotmailAccount(accounts, accountId);
  2140. if (target) {
  2141. target.status = 'error';
  2142. target.lastError = err.message;
  2143. await syncHotmailAccounts(accounts.map((item) => (item.id === target.id ? target : item)));
  2144. }
  2145. throw err;
  2146. }
  2147. }
  2148. case 'TEST_HOTMAIL_ACCOUNT': {
  2149. const result = await testHotmailAccountMailAccess(String(message.payload?.accountId || ''));
  2150. return { ok: true, ...result };
  2151. }
  2152. // Side panel data updates
  2153. case 'SAVE_EMAIL': {
  2154. const state = await getState();
  2155. if (isAutoRunLockedState(state)) {
  2156. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  2157. }
  2158. await setEmailState(message.payload.email);
  2159. await resumeAutoRun();
  2160. return { ok: true, email: message.payload.email };
  2161. }
  2162. case 'FETCH_GENERATED_EMAIL': {
  2163. clearStopRequest();
  2164. const state = await getState();
  2165. if (isAutoRunLockedState(state)) {
  2166. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  2167. }
  2168. const email = await fetchGeneratedEmail(state, message.payload || {});
  2169. await resumeAutoRun();
  2170. return { ok: true, email };
  2171. }
  2172. case 'FETCH_DUCK_EMAIL': {
  2173. clearStopRequest();
  2174. const state = await getState();
  2175. if (isAutoRunLockedState(state)) {
  2176. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  2177. }
  2178. const email = await fetchGeneratedEmail(state, { ...(message.payload || {}), generator: 'duck' });
  2179. await resumeAutoRun();
  2180. return { ok: true, email };
  2181. }
  2182. case 'STOP_FLOW': {
  2183. await requestStop();
  2184. return { ok: true };
  2185. }
  2186. default:
  2187. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  2188. return { error: `Unknown message type: ${message.type}` };
  2189. }
  2190. }
  2191. // ============================================================
  2192. // Step Data Handlers
  2193. // ============================================================
  2194. async function handleStepData(step, payload) {
  2195. switch (step) {
  2196. case 1:
  2197. if (payload.oauthUrl) {
  2198. await setState({ oauthUrl: payload.oauthUrl });
  2199. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  2200. }
  2201. break;
  2202. case 3:
  2203. if (payload.email) await setEmailState(payload.email);
  2204. if (payload.signupVerificationRequestedAt) {
  2205. await setState({ signupVerificationRequestedAt: payload.signupVerificationRequestedAt });
  2206. }
  2207. if (payload.loginVerificationRequestedAt) {
  2208. await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt });
  2209. }
  2210. break;
  2211. case 6:
  2212. if (payload.loginVerificationRequestedAt) {
  2213. await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt });
  2214. }
  2215. break;
  2216. case 4:
  2217. await setState({
  2218. lastEmailTimestamp: payload.emailTimestamp || null,
  2219. signupVerificationRequestedAt: null,
  2220. });
  2221. break;
  2222. case 7:
  2223. await setState({
  2224. lastEmailTimestamp: payload.emailTimestamp || null,
  2225. loginVerificationRequestedAt: null,
  2226. });
  2227. break;
  2228. case 8:
  2229. if (payload.localhostUrl) {
  2230. if (!isLocalhostOAuthCallbackUrl(payload.localhostUrl)) {
  2231. throw new Error('步骤 8 返回了无效的 localhost OAuth 回调地址。');
  2232. }
  2233. await setState({ localhostUrl: payload.localhostUrl });
  2234. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  2235. }
  2236. break;
  2237. case 9: {
  2238. if (payload.localhostUrl) {
  2239. await closeLocalhostCallbackTabs(payload.localhostUrl);
  2240. }
  2241. const latestState = await getState();
  2242. if (latestState.currentHotmailAccountId && isHotmailProvider(latestState)) {
  2243. await patchHotmailAccount(latestState.currentHotmailAccountId, {
  2244. used: true,
  2245. lastUsedAt: Date.now(),
  2246. });
  2247. await addLog('当前 Hotmail 账号已自动标记为已用。', 'ok');
  2248. }
  2249. const localhostPrefix = buildLocalhostCleanupPrefix(payload.localhostUrl);
  2250. if (localhostPrefix) {
  2251. await closeTabsByUrlPrefix(localhostPrefix);
  2252. }
  2253. break;
  2254. }
  2255. }
  2256. }
  2257. // ============================================================
  2258. // Step Completion Waiting
  2259. // ============================================================
  2260. // Map of step -> { resolve, reject } for waiting on step completion
  2261. const stepWaiters = new Map();
  2262. let resumeWaiter = null;
  2263. const AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS = 120000;
  2264. const AUTO_RUN_BACKGROUND_COMPLETED_STEPS = new Set([4, 7, 8]);
  2265. function waitForStepComplete(step, timeoutMs = 120000) {
  2266. return new Promise((resolve, reject) => {
  2267. throwIfStopped();
  2268. if (stepWaiters.has(step)) {
  2269. console.warn(LOG_PREFIX, `[waitForStepComplete] replacing existing waiter for step ${step}`);
  2270. }
  2271. console.log(LOG_PREFIX, `[waitForStepComplete] register step ${step}, timeout=${timeoutMs}ms`);
  2272. const timer = setTimeout(() => {
  2273. stepWaiters.delete(step);
  2274. console.warn(LOG_PREFIX, `[waitForStepComplete] timeout for step ${step} after ${timeoutMs}ms`);
  2275. reject(new Error(`步骤 ${step} 等待超时(>${timeoutMs / 1000} 秒)`));
  2276. }, timeoutMs);
  2277. stepWaiters.set(step, {
  2278. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  2279. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  2280. });
  2281. });
  2282. }
  2283. function notifyStepComplete(step, payload) {
  2284. const waiter = stepWaiters.get(step);
  2285. console.log(LOG_PREFIX, `[notifyStepComplete] step ${step}, hasWaiter=${Boolean(waiter)}`);
  2286. if (waiter) waiter.resolve(payload);
  2287. }
  2288. function notifyStepError(step, error) {
  2289. const waiter = stepWaiters.get(step);
  2290. console.warn(LOG_PREFIX, `[notifyStepError] step ${step}, hasWaiter=${Boolean(waiter)}, error=${error}`);
  2291. if (waiter) waiter.reject(new Error(error));
  2292. }
  2293. async function completeStepFromBackground(step, payload = {}) {
  2294. if (stopRequested) {
  2295. await setStepStatus(step, 'stopped');
  2296. notifyStepError(step, STOP_ERROR_MESSAGE);
  2297. return;
  2298. }
  2299. await setStepStatus(step, 'completed');
  2300. await addLog(`步骤 ${step} 已完成`, 'ok');
  2301. await handleStepData(step, payload);
  2302. notifyStepComplete(step, payload);
  2303. }
  2304. async function markRunningStepsStopped() {
  2305. const state = await getState();
  2306. const runningSteps = Object.entries(state.stepStatuses || {})
  2307. .filter(([, status]) => status === 'running')
  2308. .map(([step]) => Number(step));
  2309. for (const step of runningSteps) {
  2310. await setStepStatus(step, 'stopped');
  2311. }
  2312. }
  2313. async function requestStop(options = {}) {
  2314. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  2315. const state = await getState();
  2316. if (isAutoRunScheduledState(state) && !autoRunActive) {
  2317. await cancelScheduledAutoRun({
  2318. logMessage: options.logMessage === false
  2319. ? false
  2320. : (options.logMessage || '已取消自动运行倒计时计划。'),
  2321. });
  2322. return;
  2323. }
  2324. if (stopRequested) return;
  2325. stopRequested = true;
  2326. cancelPendingCommands();
  2327. cleanupStep8NavigationListeners();
  2328. rejectPendingStep8(new Error(STOP_ERROR_MESSAGE));
  2329. await addLog(logMessage, 'warn');
  2330. await broadcastStopToContentScripts();
  2331. for (const waiter of stepWaiters.values()) {
  2332. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  2333. }
  2334. stepWaiters.clear();
  2335. if (resumeWaiter) {
  2336. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  2337. resumeWaiter = null;
  2338. }
  2339. await markRunningStepsStopped();
  2340. autoRunActive = false;
  2341. await broadcastAutoRunStatus('stopped', {
  2342. currentRun: autoRunCurrentRun,
  2343. totalRuns: autoRunTotalRuns,
  2344. attemptRun: autoRunAttemptRun,
  2345. });
  2346. }
  2347. // ============================================================
  2348. // Step Execution
  2349. // ============================================================
  2350. async function executeStep(step) {
  2351. console.log(LOG_PREFIX, `Executing step ${step}`);
  2352. throwIfStopped();
  2353. await setStepStatus(step, 'running');
  2354. await addLog(`步骤 ${step} 开始执行`);
  2355. await humanStepDelay();
  2356. const state = await getState();
  2357. // Set flow start time on first step
  2358. if (step === 1 && !state.flowStartTime) {
  2359. await setState({ flowStartTime: Date.now() });
  2360. }
  2361. try {
  2362. switch (step) {
  2363. case 1: await executeStep1(state); break;
  2364. case 2: await executeStep2(state); break;
  2365. case 3: await executeStep3(state); break;
  2366. case 4: await executeStep4(state); break;
  2367. case 5: await executeStep5(state); break;
  2368. case 6: await executeStep6(state); break;
  2369. case 7: await executeStep7(state); break;
  2370. case 8: await executeStep8(state); break;
  2371. case 9: await executeStep9(state); break;
  2372. default:
  2373. throw new Error(`未知步骤:${step}`);
  2374. }
  2375. } catch (err) {
  2376. if (isStopError(err)) {
  2377. await setStepStatus(step, 'stopped');
  2378. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  2379. throw err;
  2380. }
  2381. await setStepStatus(step, 'failed');
  2382. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  2383. throw err;
  2384. }
  2385. }
  2386. /**
  2387. * Execute a step and wait for it to complete before returning.
  2388. * @param {number} step
  2389. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  2390. */
  2391. async function executeStepAndWait(step, delayAfter = 2000) {
  2392. throwIfStopped();
  2393. if (AUTO_RUN_BACKGROUND_COMPLETED_STEPS.has(step)) {
  2394. await addLog(`自动运行:步骤 ${step} 由后台流程负责收尾,执行函数返回后将直接进入下一步。`, 'info');
  2395. await executeStep(step);
  2396. const latestState = await getState();
  2397. await addLog(`自动运行:步骤 ${step} 已执行返回,当前状态为 ${latestState.stepStatuses?.[step] || 'pending'},准备继续后续步骤。`, 'info');
  2398. } else {
  2399. await addLog(`自动运行:步骤 ${step} 已发起,正在等待完成信号(超时 ${AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS / 1000} 秒)。`, 'info');
  2400. const completionResultPromise = waitForStepComplete(step, AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS).then(
  2401. payload => ({ ok: true, payload }),
  2402. error => ({ ok: false, error }),
  2403. );
  2404. try {
  2405. await executeStep(step);
  2406. } catch (err) {
  2407. notifyStepError(step, getErrorMessage(err));
  2408. await completionResultPromise;
  2409. throw err;
  2410. }
  2411. const completionResult = await completionResultPromise;
  2412. if (!completionResult.ok) {
  2413. throw completionResult.error;
  2414. }
  2415. await addLog(`自动运行:步骤 ${step} 已收到完成信号,准备继续后续步骤。`, 'info');
  2416. }
  2417. // Extra delay for page transitions / DOM updates
  2418. if (delayAfter > 0) {
  2419. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  2420. }
  2421. }
  2422. function getEmailGeneratorLabel(generator) {
  2423. return generator === 'cloudflare' ? 'Cloudflare 邮箱' : 'Duck 邮箱';
  2424. }
  2425. function generateCloudflareAliasLocalPart() {
  2426. const now = new Date();
  2427. const stamp = [
  2428. now.getFullYear(),
  2429. String(now.getMonth() + 1).padStart(2, '0'),
  2430. String(now.getDate()).padStart(2, '0'),
  2431. String(now.getHours()).padStart(2, '0'),
  2432. String(now.getMinutes()).padStart(2, '0'),
  2433. String(now.getSeconds()).padStart(2, '0'),
  2434. ].join('');
  2435. const randomPart = String(Math.floor(Math.random() * 900) + 100);
  2436. return `user${stamp}${randomPart}`.toLowerCase();
  2437. }
  2438. async function fetchCloudflareEmail(state, options = {}) {
  2439. throwIfStopped();
  2440. const latestState = state || await getState();
  2441. const domain = normalizeCloudflareDomain(latestState.cloudflareDomain);
  2442. if (!domain) {
  2443. throw new Error('Cloudflare 域名为空或格式无效。');
  2444. }
  2445. const localPart = String(options.localPart || '').trim().toLowerCase() || generateCloudflareAliasLocalPart();
  2446. const aliasEmail = `${localPart}@${domain}`;
  2447. await setEmailState(aliasEmail);
  2448. await addLog(`Cloudflare 邮箱:已生成 ${aliasEmail}`, 'ok');
  2449. return aliasEmail;
  2450. }
  2451. async function fetchDuckEmail(options = {}) {
  2452. throwIfStopped();
  2453. const { generateNew = true } = options;
  2454. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  2455. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  2456. const result = await sendToContentScript('duck-mail', {
  2457. type: 'FETCH_DUCK_EMAIL',
  2458. source: 'background',
  2459. payload: { generateNew },
  2460. });
  2461. if (result?.error) {
  2462. throw new Error(result.error);
  2463. }
  2464. if (!result?.email) {
  2465. throw new Error('未返回 Duck 邮箱地址。');
  2466. }
  2467. await setEmailState(result.email);
  2468. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  2469. return result.email;
  2470. }
  2471. async function fetchGeneratedEmail(state, options = {}) {
  2472. const currentState = state || await getState();
  2473. const generator = normalizeEmailGenerator(options.generator ?? currentState.emailGenerator);
  2474. if (generator === 'cloudflare') {
  2475. return fetchCloudflareEmail(currentState, options);
  2476. }
  2477. return fetchDuckEmail(options);
  2478. }
  2479. // ============================================================
  2480. // Auto Run Flow
  2481. // ============================================================
  2482. let autoRunActive = false;
  2483. let autoRunCurrentRun = 0;
  2484. let autoRunTotalRuns = 1;
  2485. let autoRunAttemptRun = 0;
  2486. const EMAIL_FETCH_MAX_ATTEMPTS = 5;
  2487. const VERIFICATION_POLL_MAX_ROUNDS = 5;
  2488. const AUTO_STEP_DELAYS = {
  2489. 1: 2000,
  2490. 2: 2000,
  2491. 3: 3000,
  2492. 4: 2000,
  2493. 5: 3000,
  2494. 6: 3000,
  2495. 7: 2000,
  2496. 8: 2000,
  2497. 9: 1000,
  2498. };
  2499. async function resumeAutoRunIfWaitingForEmail(options = {}) {
  2500. const { silent = false } = options;
  2501. const state = await getState();
  2502. if (!state.email || !isAutoRunPausedState(state)) {
  2503. return false;
  2504. }
  2505. if (resumeWaiter) {
  2506. if (!silent) {
  2507. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  2508. }
  2509. resumeWaiter.resolve();
  2510. resumeWaiter = null;
  2511. return true;
  2512. }
  2513. return false;
  2514. }
  2515. async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
  2516. const currentState = await getState();
  2517. if (isHotmailProvider(currentState)) {
  2518. const account = await ensureHotmailAccountForFlow({
  2519. allowAllocate: true,
  2520. markUsed: true,
  2521. preferredAccountId: null,
  2522. });
  2523. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:已分配 Hotmail 账号 ${account.email}(第 ${attemptRuns} 次尝试)===`, 'ok');
  2524. return account.email;
  2525. }
  2526. if (currentState.email) {
  2527. return currentState.email;
  2528. }
  2529. const generator = normalizeEmailGenerator(currentState.emailGenerator);
  2530. const generatorLabel = getEmailGeneratorLabel(generator);
  2531. let lastError = null;
  2532. for (let attempt = 1; attempt <= EMAIL_FETCH_MAX_ATTEMPTS; attempt++) {
  2533. try {
  2534. if (attempt > 1) {
  2535. await addLog(`${generatorLabel}:正在进行第 ${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS} 次自动获取重试...`, 'warn');
  2536. }
  2537. const generatedEmail = await fetchGeneratedEmail(currentState, { generateNew: true, generator });
  2538. await addLog(
  2539. `=== 目标 ${targetRun}/${totalRuns} 轮:${generatorLabel}已就绪:${generatedEmail}(第 ${attemptRuns} 次尝试,第 ${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS} 次获取)===`,
  2540. 'ok'
  2541. );
  2542. return generatedEmail;
  2543. } catch (err) {
  2544. lastError = err;
  2545. await addLog(`${generatorLabel}自动获取失败(${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS}):${err.message}`, 'warn');
  2546. if (generator === 'cloudflare' && /域名/.test(String(err.message || ''))) {
  2547. break;
  2548. }
  2549. }
  2550. }
  2551. await addLog(`${generatorLabel}自动获取已连续失败 ${EMAIL_FETCH_MAX_ATTEMPTS} 次:${lastError?.message || '未知错误'}`, 'error');
  2552. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先自动获取邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  2553. await broadcastAutoRunStatus('waiting_email', {
  2554. currentRun: targetRun,
  2555. totalRuns,
  2556. attemptRun: attemptRuns,
  2557. });
  2558. await waitForResume();
  2559. const resumedState = await getState();
  2560. if (!resumedState.email) {
  2561. throw new Error('无法继续:当前没有邮箱地址。');
  2562. }
  2563. return resumedState.email;
  2564. }
  2565. async function runAutoSequenceFromStep(startStep, context = {}) {
  2566. const { targetRun, totalRuns, attemptRuns, continued = false } = context;
  2567. const maxStep9RestartAttempts = 5;
  2568. let step9RestartAttempts = 0;
  2569. if (continued) {
  2570. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续当前进度,从步骤 ${startStep} 开始(第 ${attemptRuns} 次尝试)===`, 'info');
  2571. } else {
  2572. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  2573. }
  2574. if (startStep <= 2) {
  2575. for (const step of [1, 2]) {
  2576. if (step < startStep) continue;
  2577. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  2578. }
  2579. }
  2580. if (startStep <= 3) {
  2581. await ensureAutoEmailReady(targetRun, totalRuns, attemptRuns);
  2582. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  2583. await broadcastAutoRunStatus('running', {
  2584. currentRun: targetRun,
  2585. totalRuns,
  2586. attemptRun: attemptRuns,
  2587. });
  2588. await executeStepAndWait(3, AUTO_STEP_DELAYS[3]);
  2589. } else {
  2590. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续执行剩余流程(第 ${attemptRuns} 次尝试)===`, 'info');
  2591. }
  2592. const signupTabId = await getTabId('signup-page');
  2593. if (signupTabId) {
  2594. await chrome.tabs.update(signupTabId, { active: true });
  2595. }
  2596. let step = Math.max(startStep, 4);
  2597. while (step <= 9) {
  2598. try {
  2599. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  2600. step += 1;
  2601. } catch (err) {
  2602. const latestState = await getState();
  2603. const currentMail = getMailConfig(latestState);
  2604. const shouldRetryStep9 = step === 9
  2605. && (
  2606. isLegacyStep9RecoverableAuthError(err)
  2607. || (currentMail.provider === HOTMAIL_PROVIDER && isStep9RecoverableAuthError(err))
  2608. )
  2609. && step9RestartAttempts < maxStep9RestartAttempts;
  2610. if (shouldRetryStep9) {
  2611. step9RestartAttempts += 1;
  2612. await addLog(
  2613. `步骤 9:检测到 CPA 认证失败,正在回到步骤 6 重新开始授权流程(${step9RestartAttempts}/${maxStep9RestartAttempts})...`,
  2614. 'warn'
  2615. );
  2616. await invalidateDownstreamAfterStepRestart(6, {
  2617. logLabel: `步骤 9 认证失败后准备回到步骤 6 重试(${step9RestartAttempts}/${maxStep9RestartAttempts})`,
  2618. });
  2619. step = 6;
  2620. continue;
  2621. }
  2622. throw err;
  2623. }
  2624. }
  2625. }
  2626. // Outer loop: keep retrying until the target number of successful runs is reached.
  2627. async function autoRunLoop(totalRuns, options = {}) {
  2628. if (autoRunActive) {
  2629. await addLog('自动运行已在进行中', 'warn');
  2630. return;
  2631. }
  2632. clearStopRequest();
  2633. autoRunActive = true;
  2634. autoRunTotalRuns = totalRuns;
  2635. autoRunCurrentRun = 0;
  2636. autoRunAttemptRun = 0;
  2637. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  2638. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  2639. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) ? options.resumeCurrentRun : 0;
  2640. const resumeSuccessfulRuns = Number.isInteger(options.resumeSuccessfulRuns) ? options.resumeSuccessfulRuns : 0;
  2641. const resumeAttemptRunsProcessed = Number.isInteger(options.resumeAttemptRunsProcessed) ? options.resumeAttemptRunsProcessed : 0;
  2642. let maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  2643. const forcedRetryCap = Math.max(totalRuns * 10, totalRuns + 20);
  2644. let successfulRuns = Math.max(0, resumeSuccessfulRuns);
  2645. let attemptRuns = Math.max(0, resumeAttemptRunsProcessed);
  2646. let forceFreshTabsNextRun = false;
  2647. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  2648. await setState({
  2649. autoRunSkipFailures,
  2650. ...getAutoRunStatusPayload('running', {
  2651. currentRun: resumeCurrentRun,
  2652. totalRuns,
  2653. attemptRun: resumeAttemptRunsProcessed,
  2654. }),
  2655. });
  2656. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  2657. attemptRuns += 1;
  2658. const targetRun = successfulRuns + 1;
  2659. autoRunCurrentRun = targetRun;
  2660. autoRunAttemptRun = attemptRuns;
  2661. let startStep = 1;
  2662. let useExistingProgress = false;
  2663. if (continueCurrentOnFirstAttempt) {
  2664. const currentState = await getState();
  2665. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  2666. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  2667. startStep = resumeStep;
  2668. useExistingProgress = true;
  2669. } else if (hasSavedProgress(currentState.stepStatuses)) {
  2670. await addLog('当前流程已全部处理,将按“重新开始”新开一轮自动运行。', 'info');
  2671. }
  2672. continueCurrentOnFirstAttempt = false;
  2673. }
  2674. if (!useExistingProgress) {
  2675. // Reset everything at the start of each fresh attempt (keep user settings).
  2676. const prevState = await getState();
  2677. const keepSettings = {
  2678. vpsUrl: prevState.vpsUrl,
  2679. vpsPassword: prevState.vpsPassword,
  2680. customPassword: prevState.customPassword,
  2681. autoRunSkipFailures: prevState.autoRunSkipFailures,
  2682. autoRunDelayEnabled: prevState.autoRunDelayEnabled,
  2683. autoRunDelayMinutes: prevState.autoRunDelayMinutes,
  2684. mailProvider: prevState.mailProvider,
  2685. emailGenerator: prevState.emailGenerator,
  2686. inbucketHost: prevState.inbucketHost,
  2687. inbucketMailbox: prevState.inbucketMailbox,
  2688. cloudflareDomain: prevState.cloudflareDomain,
  2689. cloudflareDomains: prevState.cloudflareDomains,
  2690. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  2691. ...(forceFreshTabsNextRun ? { tabRegistry: {} } : {}),
  2692. };
  2693. await resetState();
  2694. await setState(keepSettings);
  2695. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => { });
  2696. await sleepWithStop(500);
  2697. } else {
  2698. await setState({
  2699. autoRunSkipFailures,
  2700. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  2701. });
  2702. }
  2703. if (forceFreshTabsNextRun) {
  2704. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  2705. forceFreshTabsNextRun = false;
  2706. }
  2707. try {
  2708. throwIfStopped();
  2709. await broadcastAutoRunStatus('running', {
  2710. currentRun: targetRun,
  2711. totalRuns,
  2712. attemptRun: attemptRuns,
  2713. });
  2714. await runAutoSequenceFromStep(startStep, {
  2715. targetRun,
  2716. totalRuns,
  2717. attemptRuns,
  2718. continued: useExistingProgress,
  2719. });
  2720. successfulRuns += 1;
  2721. autoRunCurrentRun = successfulRuns;
  2722. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  2723. continue;
  2724. } catch (err) {
  2725. if (isStopError(err)) {
  2726. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  2727. await broadcastAutoRunStatus('stopped', {
  2728. currentRun: targetRun,
  2729. totalRuns,
  2730. attemptRun: attemptRuns,
  2731. });
  2732. break;
  2733. }
  2734. if (isRestartCurrentAttemptError(err)) {
  2735. await addLog(`目标 ${targetRun}/${totalRuns} 轮检测到当前邮箱已存在,当前线程已放弃,将重新开始新一轮。`, 'warn');
  2736. cancelPendingCommands('当前线程因邮箱已存在而放弃。');
  2737. await broadcastStopToContentScripts();
  2738. await broadcastAutoRunStatus('retrying', {
  2739. currentRun: targetRun,
  2740. totalRuns,
  2741. attemptRun: attemptRuns,
  2742. });
  2743. forceFreshTabsNextRun = true;
  2744. maxAttempts = Math.max(maxAttempts, Math.min(forcedRetryCap, attemptRuns + 1));
  2745. continue;
  2746. }
  2747. if (!autoRunSkipFailures) {
  2748. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  2749. await broadcastAutoRunStatus('stopped', {
  2750. currentRun: targetRun,
  2751. totalRuns,
  2752. attemptRun: attemptRuns,
  2753. });
  2754. break;
  2755. }
  2756. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  2757. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  2758. cancelPendingCommands('当前尝试已放弃。');
  2759. await broadcastStopToContentScripts();
  2760. await broadcastAutoRunStatus('retrying', {
  2761. currentRun: targetRun,
  2762. totalRuns,
  2763. attemptRun: attemptRuns,
  2764. });
  2765. forceFreshTabsNextRun = true;
  2766. }
  2767. }
  2768. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  2769. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  2770. await broadcastAutoRunStatus('stopped', {
  2771. currentRun: successfulRuns,
  2772. totalRuns: autoRunTotalRuns,
  2773. attemptRun: attemptRuns,
  2774. });
  2775. } else if (stopRequested) {
  2776. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  2777. await broadcastAutoRunStatus('stopped', {
  2778. currentRun: successfulRuns,
  2779. totalRuns: autoRunTotalRuns,
  2780. attemptRun: attemptRuns,
  2781. });
  2782. } else if (successfulRuns >= autoRunTotalRuns) {
  2783. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  2784. await broadcastAutoRunStatus('complete', {
  2785. currentRun: successfulRuns,
  2786. totalRuns: autoRunTotalRuns,
  2787. attemptRun: attemptRuns,
  2788. });
  2789. } else {
  2790. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  2791. await broadcastAutoRunStatus('stopped', {
  2792. currentRun: successfulRuns,
  2793. totalRuns: autoRunTotalRuns,
  2794. attemptRun: attemptRuns,
  2795. });
  2796. }
  2797. autoRunActive = false;
  2798. autoRunAttemptRun = attemptRuns;
  2799. await setState(getAutoRunStatusPayload(stopRequested ? 'stopped' : (successfulRuns >= autoRunTotalRuns ? 'complete' : 'stopped'), {
  2800. currentRun: successfulRuns,
  2801. totalRuns: autoRunTotalRuns,
  2802. attemptRun: attemptRuns,
  2803. }));
  2804. clearStopRequest();
  2805. }
  2806. async function waitForResume() {
  2807. throwIfStopped();
  2808. const state = await getState();
  2809. if (state.email) {
  2810. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  2811. return;
  2812. }
  2813. return new Promise((resolve, reject) => {
  2814. resumeWaiter = { resolve, reject };
  2815. });
  2816. }
  2817. async function resumeAutoRun() {
  2818. throwIfStopped();
  2819. const state = await getState();
  2820. if (!state.email) {
  2821. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  2822. return false;
  2823. }
  2824. const resumedInMemory = await resumeAutoRunIfWaitingForEmail({ silent: true });
  2825. if (resumedInMemory) {
  2826. return true;
  2827. }
  2828. if (!isAutoRunPausedState(state)) {
  2829. return false;
  2830. }
  2831. if (autoRunActive) {
  2832. return false;
  2833. }
  2834. const totalRuns = state.autoRunTotalRuns || 1;
  2835. const currentRun = state.autoRunCurrentRun || 1;
  2836. const attemptRun = state.autoRunAttemptRun || 1;
  2837. const successfulRuns = Math.max(0, currentRun - 1);
  2838. await addLog('检测到自动流程暂停上下文已丢失,正在从当前进度恢复自动运行...', 'warn');
  2839. autoRunLoop(totalRuns, {
  2840. autoRunSkipFailures: Boolean(state.autoRunSkipFailures),
  2841. mode: 'continue',
  2842. resumeCurrentRun: currentRun,
  2843. resumeSuccessfulRuns: successfulRuns,
  2844. resumeAttemptRunsProcessed: Math.max(0, attemptRun - 1),
  2845. });
  2846. return true;
  2847. }
  2848. // ============================================================
  2849. // Step 1: Get OAuth Link (via vps-panel.js)
  2850. // ============================================================
  2851. async function executeStep1(state) {
  2852. if (!state.vpsUrl) {
  2853. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  2854. }
  2855. await addLog('步骤 1:正在打开 CPA 面板...');
  2856. const injectFiles = ['content/activation-utils.js', 'content/utils.js', 'content/vps-panel.js'];
  2857. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  2858. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  2859. const tabId = tab.id;
  2860. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  2861. await addLog('步骤 1:CPA 面板已打开,正在等待页面进入目标地址...');
  2862. const matchedTab = await waitForTabUrlFamily('vps-panel', tabId, state.vpsUrl, {
  2863. timeoutMs: 15000,
  2864. retryDelayMs: 400,
  2865. });
  2866. if (!matchedTab) {
  2867. await addLog('步骤 1:CPA 页面尚未完全进入目标地址,继续尝试连接内容脚本...', 'warn');
  2868. }
  2869. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  2870. inject: injectFiles,
  2871. timeoutMs: 45000,
  2872. retryDelayMs: 900,
  2873. logMessage: '步骤 1:CPA 面板仍在加载,正在重试连接内容脚本...',
  2874. });
  2875. const result = await sendToContentScriptResilient('vps-panel', {
  2876. type: 'EXECUTE_STEP',
  2877. step: 1,
  2878. source: 'background',
  2879. payload: { vpsPassword: state.vpsPassword },
  2880. }, {
  2881. timeoutMs: 30000,
  2882. retryDelayMs: 700,
  2883. logMessage: '步骤 1:CPA 面板通信未就绪,正在等待页面恢复...',
  2884. });
  2885. if (result?.error) {
  2886. throw new Error(result.error);
  2887. }
  2888. }
  2889. // ============================================================
  2890. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  2891. // ============================================================
  2892. async function executeStep2(state) {
  2893. if (!state.oauthUrl) {
  2894. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  2895. }
  2896. await addLog('步骤 2:正在打开认证链接...');
  2897. await reuseOrCreateTab('signup-page', state.oauthUrl);
  2898. await sendToContentScript('signup-page', {
  2899. type: 'EXECUTE_STEP',
  2900. step: 2,
  2901. source: 'background',
  2902. payload: {},
  2903. });
  2904. }
  2905. // ============================================================
  2906. // Step 3: Fill Email & Password (via signup-page.js)
  2907. // ============================================================
  2908. async function executeStep3(state) {
  2909. let resolvedEmail = state.email;
  2910. if (isHotmailProvider(state)) {
  2911. const account = await ensureHotmailAccountForFlow({
  2912. allowAllocate: true,
  2913. markUsed: true,
  2914. preferredAccountId: state.currentHotmailAccountId || null,
  2915. });
  2916. resolvedEmail = account.email;
  2917. }
  2918. if (!resolvedEmail) {
  2919. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  2920. }
  2921. const password = state.customPassword || generatePassword();
  2922. if (resolvedEmail !== state.email) {
  2923. await setEmailState(resolvedEmail);
  2924. }
  2925. await setPasswordState(password);
  2926. // Save account record
  2927. const accounts = state.accounts || [];
  2928. accounts.push({ email: resolvedEmail, password, createdAt: new Date().toISOString() });
  2929. await setState({ accounts });
  2930. await addLog(
  2931. `步骤 3:正在填写邮箱 ${resolvedEmail},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  2932. );
  2933. await sendToContentScript('signup-page', {
  2934. type: 'EXECUTE_STEP',
  2935. step: 3,
  2936. source: 'background',
  2937. payload: { email: resolvedEmail, password },
  2938. });
  2939. }
  2940. // ============================================================
  2941. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  2942. // ============================================================
  2943. function getMailConfig(state) {
  2944. const provider = state.mailProvider || 'qq';
  2945. if (provider === HOTMAIL_PROVIDER) {
  2946. return { provider: HOTMAIL_PROVIDER, label: 'Hotmail(微软 Graph)' };
  2947. }
  2948. if (provider === '163') {
  2949. 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 邮箱' };
  2950. }
  2951. if (provider === '163-vip') {
  2952. 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 邮箱' };
  2953. }
  2954. if (provider === 'inbucket') {
  2955. const host = normalizeInbucketOrigin(state.inbucketHost);
  2956. const mailbox = (state.inbucketMailbox || '').trim();
  2957. if (!host) {
  2958. return { error: 'Inbucket 主机地址为空或无效。' };
  2959. }
  2960. if (!mailbox) {
  2961. return { error: 'Inbucket 邮箱名称为空。' };
  2962. }
  2963. return {
  2964. source: 'inbucket-mail',
  2965. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  2966. label: `Inbucket 邮箱(${mailbox})`,
  2967. navigateOnReuse: true,
  2968. inject: ['content/activation-utils.js', 'content/utils.js', 'content/inbucket-mail.js'],
  2969. injectSource: 'inbucket-mail',
  2970. };
  2971. }
  2972. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  2973. }
  2974. function normalizeInbucketOrigin(rawValue) {
  2975. const value = (rawValue || '').trim();
  2976. if (!value) return '';
  2977. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  2978. try {
  2979. const parsed = new URL(candidate);
  2980. return parsed.origin;
  2981. } catch {
  2982. return '';
  2983. }
  2984. }
  2985. function getVerificationCodeStateKey(step) {
  2986. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  2987. }
  2988. function getVerificationCodeLabel(step) {
  2989. return step === 4 ? '注册' : '登录';
  2990. }
  2991. function getVerificationPollPayload(step, state, overrides = {}) {
  2992. if (step === 4) {
  2993. return {
  2994. filterAfterTimestamp: getHotmailVerificationRequestTimestamp(4, state),
  2995. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  2996. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  2997. targetEmail: state.email,
  2998. maxAttempts: 5,
  2999. intervalMs: 3000,
  3000. ...overrides,
  3001. };
  3002. }
  3003. return {
  3004. filterAfterTimestamp: getHotmailVerificationRequestTimestamp(7, state),
  3005. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  3006. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  3007. targetEmail: state.email,
  3008. maxAttempts: 5,
  3009. intervalMs: 3000,
  3010. ...overrides,
  3011. };
  3012. }
  3013. async function requestVerificationCodeResend(step) {
  3014. const signupTabId = await getTabId('signup-page');
  3015. if (!signupTabId) {
  3016. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  3017. }
  3018. await chrome.tabs.update(signupTabId, { active: true });
  3019. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  3020. const result = await sendToContentScript('signup-page', {
  3021. type: 'RESEND_VERIFICATION_CODE',
  3022. step,
  3023. source: 'background',
  3024. payload: {},
  3025. });
  3026. if (step === 7) {
  3027. const restartError = getStep7RestartFromStep6Error(result);
  3028. if (restartError) {
  3029. throw restartError;
  3030. }
  3031. }
  3032. if (result && result.error) {
  3033. throw new Error(result.error);
  3034. }
  3035. return Date.now();
  3036. }
  3037. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  3038. if (mail.provider === HOTMAIL_PROVIDER) {
  3039. const hotmailPollConfig = getHotmailVerificationPollConfig(step);
  3040. return pollHotmailVerificationCode(step, state, {
  3041. ...getVerificationPollPayload(step, state),
  3042. ...hotmailPollConfig,
  3043. ...pollOverrides,
  3044. });
  3045. }
  3046. const stateKey = getVerificationCodeStateKey(step);
  3047. const rejectedCodes = new Set();
  3048. if (state[stateKey]) {
  3049. rejectedCodes.add(state[stateKey]);
  3050. }
  3051. for (const code of (pollOverrides.excludeCodes || [])) {
  3052. if (code) rejectedCodes.add(code);
  3053. }
  3054. let lastError = null;
  3055. const filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  3056. const maxRounds = pollOverrides.maxRounds || VERIFICATION_POLL_MAX_ROUNDS;
  3057. for (let round = 1; round <= maxRounds; round++) {
  3058. if (round > 1) {
  3059. await requestVerificationCodeResend(step);
  3060. }
  3061. const payload = getVerificationPollPayload(step, state, {
  3062. ...pollOverrides,
  3063. filterAfterTimestamp,
  3064. excludeCodes: [...rejectedCodes],
  3065. });
  3066. try {
  3067. const result = await sendToMailContentScriptResilient(
  3068. mail,
  3069. {
  3070. type: 'POLL_EMAIL',
  3071. step,
  3072. source: 'background',
  3073. payload,
  3074. },
  3075. {
  3076. timeoutMs: 45000,
  3077. maxRecoveryAttempts: 2,
  3078. }
  3079. );
  3080. if (result && result.error) {
  3081. throw new Error(result.error);
  3082. }
  3083. if (!result || !result.code) {
  3084. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  3085. }
  3086. if (rejectedCodes.has(result.code)) {
  3087. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  3088. }
  3089. return result;
  3090. } catch (err) {
  3091. lastError = err;
  3092. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  3093. if (round < maxRounds) {
  3094. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  3095. }
  3096. }
  3097. }
  3098. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  3099. }
  3100. async function submitVerificationCode(step, code) {
  3101. const signupTabId = await getTabId('signup-page');
  3102. if (!signupTabId) {
  3103. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  3104. }
  3105. await chrome.tabs.update(signupTabId, { active: true });
  3106. const result = await sendToContentScript('signup-page', {
  3107. type: 'FILL_CODE',
  3108. step,
  3109. source: 'background',
  3110. payload: { code },
  3111. });
  3112. if (step === 7) {
  3113. const restartError = getStep7RestartFromStep6Error(result);
  3114. if (restartError) {
  3115. throw restartError;
  3116. }
  3117. }
  3118. if (result && result.error) {
  3119. throw new Error(result.error);
  3120. }
  3121. return result || {};
  3122. }
  3123. async function resolveVerificationStep(step, state, mail, options = {}) {
  3124. const stateKey = getVerificationCodeStateKey(step);
  3125. const rejectedCodes = new Set();
  3126. const hotmailPollConfig = mail.provider === HOTMAIL_PROVIDER
  3127. ? getHotmailVerificationPollConfig(step)
  3128. : null;
  3129. const ignorePersistedLastCode = Boolean(hotmailPollConfig?.ignorePersistedLastCode);
  3130. if (state[stateKey] && !ignorePersistedLastCode) {
  3131. rejectedCodes.add(state[stateKey]);
  3132. }
  3133. const nextFilterAfterTimestamp = options.filterAfterTimestamp ?? null;
  3134. const requestFreshCodeFirst = options.requestFreshCodeFirst !== undefined
  3135. ? Boolean(options.requestFreshCodeFirst)
  3136. : (hotmailPollConfig?.requestFreshCodeFirst ?? false);
  3137. const maxSubmitAttempts = 3;
  3138. if (requestFreshCodeFirst) {
  3139. try {
  3140. await requestVerificationCodeResend(step);
  3141. await addLog(`步骤 ${step}:已先请求一封新的${getVerificationCodeLabel(step)}验证码,再开始轮询邮箱。`, 'warn');
  3142. } catch (err) {
  3143. if (step === 7 && isStep7RestartFromStep6Error(err)) {
  3144. throw err;
  3145. }
  3146. await addLog(`步骤 ${step}:首次重新获取验证码失败:${err.message},将继续使用当前时间窗口轮询。`, 'warn');
  3147. }
  3148. }
  3149. if (mail.provider === HOTMAIL_PROVIDER) {
  3150. const initialDelayMs = Number(options.initialDelayMs ?? hotmailPollConfig.initialDelayMs) || 0;
  3151. if (initialDelayMs > 0) {
  3152. await addLog(`步骤 ${step}:等待 ${Math.round(initialDelayMs / 1000)} 秒,让 Hotmail 验证码邮件先到达...`, 'info');
  3153. await sleepWithStop(initialDelayMs);
  3154. }
  3155. }
  3156. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  3157. const result = await pollFreshVerificationCode(step, state, mail, {
  3158. excludeCodes: [...rejectedCodes],
  3159. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  3160. });
  3161. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  3162. const submitResult = await submitVerificationCode(step, result.code);
  3163. if (submitResult.invalidCode) {
  3164. rejectedCodes.add(result.code);
  3165. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  3166. if (attempt >= maxSubmitAttempts) {
  3167. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  3168. }
  3169. await requestVerificationCodeResend(step);
  3170. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  3171. continue;
  3172. }
  3173. await setState({
  3174. lastEmailTimestamp: result.emailTimestamp,
  3175. [stateKey]: result.code,
  3176. });
  3177. await completeStepFromBackground(step, {
  3178. emailTimestamp: result.emailTimestamp,
  3179. code: result.code,
  3180. });
  3181. return;
  3182. }
  3183. }
  3184. async function executeStep4(state) {
  3185. const mail = getMailConfig(state);
  3186. if (mail.error) throw new Error(mail.error);
  3187. const stepStartedAt = Date.now();
  3188. const signupTabId = await getTabId('signup-page');
  3189. if (!signupTabId) {
  3190. throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
  3191. }
  3192. await chrome.tabs.update(signupTabId, { active: true });
  3193. await addLog('步骤 4:正在确认注册验证码页面是否就绪,必要时自动恢复密码页超时报错...');
  3194. const prepareResult = await sendToContentScriptResilient(
  3195. 'signup-page',
  3196. {
  3197. type: 'PREPARE_SIGNUP_VERIFICATION',
  3198. step: 4,
  3199. source: 'background',
  3200. payload: { password: state.password || state.customPassword || '' },
  3201. },
  3202. {
  3203. timeoutMs: 30000,
  3204. retryDelayMs: 700,
  3205. logMessage: '步骤 4:认证页正在切换,等待页面重新就绪后继续检测...',
  3206. }
  3207. );
  3208. if (prepareResult && prepareResult.error) {
  3209. throw new Error(prepareResult.error);
  3210. }
  3211. if (prepareResult?.verificationRequestedAt) {
  3212. await setState({ loginVerificationRequestedAt: prepareResult.verificationRequestedAt });
  3213. }
  3214. if (prepareResult?.alreadyVerified) {
  3215. await completeStepFromBackground(4, {});
  3216. return;
  3217. }
  3218. if (mail.provider === HOTMAIL_PROVIDER) {
  3219. await addLog(`步骤 4:正在通过 ${mail.label} 轮询验证码...`);
  3220. } else {
  3221. await addLog(`步骤 4:正在打开${mail.label}...`);
  3222. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  3223. const alive = await isTabAlive(mail.source);
  3224. if (alive) {
  3225. if (mail.navigateOnReuse) {
  3226. await reuseOrCreateTab(mail.source, mail.url, {
  3227. inject: mail.inject,
  3228. injectSource: mail.injectSource,
  3229. });
  3230. } else {
  3231. const tabId = await getTabId(mail.source);
  3232. await chrome.tabs.update(tabId, { active: true });
  3233. }
  3234. } else {
  3235. await reuseOrCreateTab(mail.source, mail.url, {
  3236. inject: mail.inject,
  3237. injectSource: mail.injectSource,
  3238. });
  3239. }
  3240. }
  3241. await resolveVerificationStep(4, state, mail, {
  3242. filterAfterTimestamp: mail.provider === HOTMAIL_PROVIDER ? undefined : stepStartedAt,
  3243. requestFreshCodeFirst: mail.provider === HOTMAIL_PROVIDER ? false : true,
  3244. });
  3245. return;
  3246. }
  3247. // ============================================================
  3248. // Step 5: Fill Name & Birthday (via signup-page.js)
  3249. // ============================================================
  3250. async function executeStep5(state) {
  3251. const { firstName, lastName } = generateRandomName();
  3252. const { year, month, day } = generateRandomBirthday();
  3253. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  3254. await sendToContentScript('signup-page', {
  3255. type: 'EXECUTE_STEP',
  3256. step: 5,
  3257. source: 'background',
  3258. payload: { firstName, lastName, year, month, day },
  3259. });
  3260. }
  3261. // ============================================================
  3262. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  3263. // ============================================================
  3264. async function refreshOAuthUrlBeforeStep6(state) {
  3265. if (!state.vpsUrl) {
  3266. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  3267. }
  3268. await addLog('步骤 6:正在刷新登录用的 CPA OAuth 链接...');
  3269. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] preparing fresh OAuth via step 1');
  3270. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  3271. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] executing step 1 for fresh OAuth');
  3272. await executeStep1(state);
  3273. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 execute returned, waiting for completion signal');
  3274. await waitForFreshOAuth;
  3275. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 completion signal received');
  3276. const latestState = await getState();
  3277. if (!latestState.oauthUrl) {
  3278. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  3279. }
  3280. return latestState.oauthUrl;
  3281. }
  3282. async function executeStep6(state) {
  3283. if (!state.email) {
  3284. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  3285. }
  3286. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  3287. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  3288. // Reuse the signup-page tab — navigate it to the OAuth URL
  3289. await reuseOrCreateTab('signup-page', oauthUrl);
  3290. // signup-page.js will inject (same auth.openai.com domain) and handle login
  3291. await sendToContentScript('signup-page', {
  3292. type: 'EXECUTE_STEP',
  3293. step: 6,
  3294. source: 'background',
  3295. payload: { email: state.email, password: state.password },
  3296. });
  3297. }
  3298. // ============================================================
  3299. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  3300. // ============================================================
  3301. async function runStep7Attempt(state) {
  3302. const mail = getMailConfig(state);
  3303. if (mail.error) throw new Error(mail.error);
  3304. const stepStartedAt = Date.now();
  3305. const authTabId = await getTabId('signup-page');
  3306. if (authTabId) {
  3307. await chrome.tabs.update(authTabId, { active: true });
  3308. } else {
  3309. if (!state.oauthUrl) {
  3310. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  3311. }
  3312. await reuseOrCreateTab('signup-page', state.oauthUrl);
  3313. }
  3314. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  3315. const prepareResult = await sendToContentScript('signup-page', {
  3316. type: 'PREPARE_LOGIN_CODE',
  3317. step: 7,
  3318. source: 'background',
  3319. payload: {},
  3320. });
  3321. const restartError = getStep7RestartFromStep6Error(prepareResult);
  3322. if (restartError) {
  3323. throw restartError;
  3324. }
  3325. if (prepareResult && prepareResult.error) {
  3326. throw new Error(prepareResult.error);
  3327. }
  3328. if (mail.provider === HOTMAIL_PROVIDER) {
  3329. await addLog(`步骤 7:正在通过 ${mail.label} 轮询验证码...`);
  3330. } else {
  3331. await addLog(`步骤 7:正在打开${mail.label}...`);
  3332. const alive = await isTabAlive(mail.source);
  3333. if (alive) {
  3334. if (mail.navigateOnReuse) {
  3335. await reuseOrCreateTab(mail.source, mail.url, {
  3336. inject: mail.inject,
  3337. injectSource: mail.injectSource,
  3338. });
  3339. } else {
  3340. const tabId = await getTabId(mail.source);
  3341. await chrome.tabs.update(tabId, { active: true });
  3342. }
  3343. } else {
  3344. await reuseOrCreateTab(mail.source, mail.url, {
  3345. inject: mail.inject,
  3346. injectSource: mail.injectSource,
  3347. });
  3348. }
  3349. }
  3350. await resolveVerificationStep(7, state, mail, {
  3351. filterAfterTimestamp: mail.provider === HOTMAIL_PROVIDER ? undefined : stepStartedAt,
  3352. requestFreshCodeFirst: mail.provider === HOTMAIL_PROVIDER ? false : true,
  3353. });
  3354. }
  3355. async function rerunStep6ForStep7Recovery() {
  3356. const currentState = await getState();
  3357. const waitForStep6 = waitForStepComplete(6, 120000);
  3358. await addLog('步骤 7:正在回到步骤 6,重新发起登录验证码流程...', 'warn');
  3359. await executeStep6(currentState);
  3360. await waitForStep6;
  3361. await sleepWithStop(3000);
  3362. }
  3363. async function executeStep7(state) {
  3364. let lastError = null;
  3365. for (let round = 1; round <= STEP7_RESTART_MAX_ROUNDS; round++) {
  3366. const currentState = round === 1 ? state : await getState();
  3367. try {
  3368. if (round > 1) {
  3369. await addLog(`步骤 7:正在进行第 ${round}/${STEP7_RESTART_MAX_ROUNDS} 轮登录验证码恢复尝试。`, 'warn');
  3370. }
  3371. await runStep7Attempt(currentState);
  3372. return;
  3373. } catch (err) {
  3374. lastError = err;
  3375. if (!isStep7RecoverableError(err)) {
  3376. throw err;
  3377. }
  3378. if (round >= STEP7_RESTART_MAX_ROUNDS) {
  3379. break;
  3380. }
  3381. await addLog(
  3382. isStep7RestartFromStep6Error(err)
  3383. ? `步骤 7:检测到登录页超时报错,准备从步骤 6 重新开始(${round + 1}/${STEP7_RESTART_MAX_ROUNDS})...`
  3384. : `步骤 7:检测到邮箱轮询类失败,准备从步骤 6 重新开始(${round + 1}/${STEP7_RESTART_MAX_ROUNDS})...`,
  3385. 'warn'
  3386. );
  3387. await rerunStep6ForStep7Recovery();
  3388. }
  3389. }
  3390. if (lastError && isStep7RecoverableError(lastError)) {
  3391. throw new Error(`步骤 7:登录验证码流程在 ${STEP7_RESTART_MAX_ROUNDS} 轮恢复后仍未成功。最后一次原因:${lastError.message}`);
  3392. }
  3393. throw lastError || new Error(`步骤 7:登录验证码流程在 ${STEP7_RESTART_MAX_ROUNDS} 轮后仍未成功。`);
  3394. }
  3395. // ============================================================
  3396. // Step 8: 完成 OAuth(自动点击 + localhost 回调监听)
  3397. // ============================================================
  3398. let webNavListener = null;
  3399. let webNavCommittedListener = null;
  3400. let step8TabUpdatedListener = null;
  3401. let step8PendingReject = null;
  3402. const STEP8_CLICK_EFFECT_TIMEOUT_MS = 10000;
  3403. const STEP8_CLICK_RETRY_DELAY_MS = 500;
  3404. const STEP8_READY_WAIT_TIMEOUT_MS = 30000;
  3405. const STEP8_MAX_ROUNDS = 5;
  3406. const STEP8_SIGNUP_PAGE_INJECT_FILES = ['content/utils.js', 'content/signup-page.js'];
  3407. const STEP8_STRATEGIES = [
  3408. { mode: 'content', strategy: 'requestSubmit', label: 'form.requestSubmit' },
  3409. { mode: 'debugger', label: 'debugger click' },
  3410. { mode: 'content', strategy: 'nativeClick', label: 'element.click' },
  3411. { mode: 'content', strategy: 'dispatchClick', label: 'dispatch click' },
  3412. { mode: 'debugger', label: 'debugger click retry' },
  3413. ];
  3414. function cleanupStep8NavigationListeners() {
  3415. if (webNavListener) {
  3416. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  3417. webNavListener = null;
  3418. }
  3419. if (webNavCommittedListener) {
  3420. chrome.webNavigation.onCommitted.removeListener(webNavCommittedListener);
  3421. webNavCommittedListener = null;
  3422. }
  3423. if (step8TabUpdatedListener) {
  3424. chrome.tabs.onUpdated.removeListener(step8TabUpdatedListener);
  3425. step8TabUpdatedListener = null;
  3426. }
  3427. }
  3428. function rejectPendingStep8(error) {
  3429. if (!step8PendingReject) return;
  3430. const reject = step8PendingReject;
  3431. step8PendingReject = null;
  3432. reject(error);
  3433. }
  3434. function throwIfStep8SettledOrStopped(isSettled = false) {
  3435. if (isSettled || stopRequested) {
  3436. throw new Error(STOP_ERROR_MESSAGE);
  3437. }
  3438. }
  3439. async function ensureStep8SignupPageReady(tabId, options = {}) {
  3440. await ensureContentScriptReadyOnTab('signup-page', tabId, {
  3441. inject: STEP8_SIGNUP_PAGE_INJECT_FILES,
  3442. injectSource: 'signup-page',
  3443. timeoutMs: options.timeoutMs ?? 15000,
  3444. retryDelayMs: options.retryDelayMs ?? 600,
  3445. logMessage: options.logMessage || '',
  3446. });
  3447. }
  3448. async function getStep8PageState(tabId, responseTimeoutMs = 1500) {
  3449. try {
  3450. const result = await sendTabMessageWithTimeout(tabId, 'signup-page', {
  3451. type: 'STEP8_GET_STATE',
  3452. source: 'background',
  3453. payload: {},
  3454. }, responseTimeoutMs);
  3455. if (result?.error) {
  3456. throw new Error(result.error);
  3457. }
  3458. return result;
  3459. } catch (err) {
  3460. if (isRetryableContentScriptTransportError(err)) {
  3461. return null;
  3462. }
  3463. throw err;
  3464. }
  3465. }
  3466. async function waitForStep8Ready(tabId, timeoutMs = STEP8_READY_WAIT_TIMEOUT_MS) {
  3467. const start = Date.now();
  3468. let recovered = false;
  3469. while (Date.now() - start < timeoutMs) {
  3470. throwIfStopped();
  3471. const pageState = await getStep8PageState(tabId);
  3472. if (pageState?.addPhonePage) {
  3473. throw new Error('步骤 8:认证页进入了手机号页面,当前不是 OAuth 同意页,无法继续自动授权。');
  3474. }
  3475. if (pageState?.consentReady) {
  3476. return pageState;
  3477. }
  3478. if (pageState === null && !recovered) {
  3479. recovered = true;
  3480. await ensureStep8SignupPageReady(tabId, {
  3481. timeoutMs: Math.min(10000, timeoutMs),
  3482. logMessage: '步骤 8:认证页内容脚本已失联,正在等待页面重新就绪...',
  3483. });
  3484. continue;
  3485. }
  3486. recovered = false;
  3487. await sleepWithStop(250);
  3488. }
  3489. throw new Error('步骤 8:长时间未进入 OAuth 同意页,无法定位“继续”按钮。');
  3490. }
  3491. async function prepareStep8DebuggerClick(tabId) {
  3492. await ensureStep8SignupPageReady(tabId, {
  3493. timeoutMs: 15000,
  3494. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续定位按钮...',
  3495. });
  3496. const result = await sendToContentScriptResilient('signup-page', {
  3497. type: 'STEP8_FIND_AND_CLICK',
  3498. source: 'background',
  3499. payload: {},
  3500. }, {
  3501. timeoutMs: 15000,
  3502. retryDelayMs: 600,
  3503. logMessage: '步骤 8:认证页正在切换,等待 OAuth 同意页按钮重新就绪...',
  3504. });
  3505. if (result?.error) {
  3506. throw new Error(result.error);
  3507. }
  3508. return result;
  3509. }
  3510. async function triggerStep8ContentStrategy(tabId, strategy) {
  3511. await ensureStep8SignupPageReady(tabId, {
  3512. timeoutMs: 15000,
  3513. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续点击“继续”按钮...',
  3514. });
  3515. const result = await sendToContentScriptResilient('signup-page', {
  3516. type: 'STEP8_TRIGGER_CONTINUE',
  3517. source: 'background',
  3518. payload: {
  3519. strategy,
  3520. findTimeoutMs: 4000,
  3521. enabledTimeoutMs: 3000,
  3522. },
  3523. }, {
  3524. timeoutMs: 15000,
  3525. retryDelayMs: 600,
  3526. logMessage: '步骤 8:认证页正在切换,等待“继续”按钮重新就绪...',
  3527. });
  3528. if (result?.error) {
  3529. throw new Error(result.error);
  3530. }
  3531. return result;
  3532. }
  3533. async function reloadStep8ConsentPage(tabId, timeoutMs = 30000) {
  3534. if (!Number.isInteger(tabId)) {
  3535. throw new Error('步骤 8:缺少有效的认证页标签页,无法刷新后重试。');
  3536. }
  3537. await chrome.tabs.update(tabId, { active: true }).catch(() => { });
  3538. await new Promise((resolve, reject) => {
  3539. let settled = false;
  3540. const timer = setTimeout(() => {
  3541. if (settled) return;
  3542. settled = true;
  3543. chrome.tabs.onUpdated.removeListener(listener);
  3544. reject(new Error('步骤 8:刷新认证页后等待页面完成加载超时。'));
  3545. }, timeoutMs);
  3546. const listener = (updatedTabId, changeInfo) => {
  3547. if (updatedTabId !== tabId) return;
  3548. if (changeInfo.status !== 'complete') return;
  3549. if (settled) return;
  3550. settled = true;
  3551. clearTimeout(timer);
  3552. chrome.tabs.onUpdated.removeListener(listener);
  3553. resolve();
  3554. };
  3555. chrome.tabs.onUpdated.addListener(listener);
  3556. chrome.tabs.reload(tabId, { bypassCache: false }).catch((err) => {
  3557. if (settled) return;
  3558. settled = true;
  3559. clearTimeout(timer);
  3560. chrome.tabs.onUpdated.removeListener(listener);
  3561. reject(err);
  3562. });
  3563. });
  3564. await ensureStep8SignupPageReady(tabId, {
  3565. timeoutMs: Math.min(15000, timeoutMs),
  3566. logMessage: '步骤 8:认证页刷新后内容脚本尚未就绪,正在等待页面恢复...',
  3567. });
  3568. }
  3569. async function waitForStep8ClickEffect(tabId, baselineUrl, timeoutMs = STEP8_CLICK_EFFECT_TIMEOUT_MS) {
  3570. const start = Date.now();
  3571. let recovered = false;
  3572. while (Date.now() - start < timeoutMs) {
  3573. throwIfStopped();
  3574. const tab = await chrome.tabs.get(tabId).catch(() => null);
  3575. if (!tab) {
  3576. throw new Error('步骤 8:认证页面标签页已关闭,无法继续自动授权。');
  3577. }
  3578. if (baselineUrl && typeof tab.url === 'string' && tab.url !== baselineUrl) {
  3579. return { progressed: true, reason: 'url_changed', url: tab.url };
  3580. }
  3581. const pageState = await getStep8PageState(tabId);
  3582. if (pageState?.addPhonePage) {
  3583. throw new Error('步骤 8:点击“继续”后页面跳到了手机号页面,当前流程无法继续自动授权。');
  3584. }
  3585. if (pageState === null) {
  3586. if (!recovered) {
  3587. recovered = true;
  3588. await ensureStep8SignupPageReady(tabId, {
  3589. timeoutMs: Math.max(3000, Math.min(8000, timeoutMs)),
  3590. logMessage: '步骤 8:点击后认证页正在重载,正在等待内容脚本重新就绪...',
  3591. }).catch(() => null);
  3592. continue;
  3593. }
  3594. await sleepWithStop(200);
  3595. continue;
  3596. }
  3597. recovered = false;
  3598. await sleepWithStop(200);
  3599. }
  3600. return { progressed: false, reason: 'no_effect' };
  3601. }
  3602. function getStep8EffectLabel(effect) {
  3603. switch (effect?.reason) {
  3604. case 'url_changed':
  3605. return `URL 已变化:${effect.url}`;
  3606. case 'page_reloading':
  3607. return '页面正在跳转或重载';
  3608. case 'left_consent_page':
  3609. return `页面已离开 OAuth 同意页:${effect.url || 'unknown'}`;
  3610. default:
  3611. return '页面仍停留在 OAuth 同意页';
  3612. }
  3613. }
  3614. async function executeStep8(state) {
  3615. if (!state.oauthUrl) {
  3616. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  3617. }
  3618. await addLog('步骤 8:正在监听 localhost 回调地址...');
  3619. return new Promise((resolve, reject) => {
  3620. let resolved = false;
  3621. let signupTabId = null;
  3622. const cleanupListener = () => {
  3623. cleanupStep8NavigationListeners();
  3624. step8PendingReject = null;
  3625. };
  3626. const rejectStep8 = (error) => {
  3627. if (resolved) return;
  3628. resolved = true;
  3629. clearTimeout(timeout);
  3630. cleanupListener();
  3631. reject(error);
  3632. };
  3633. const finalizeStep8Callback = (callbackUrl) => {
  3634. if (resolved || !callbackUrl) return;
  3635. resolved = true;
  3636. cleanupListener();
  3637. clearTimeout(timeout);
  3638. addLog(`步骤 8:已捕获 localhost 地址:${callbackUrl}`, 'ok').then(() => {
  3639. return completeStepFromBackground(8, { localhostUrl: callbackUrl });
  3640. }).then(() => {
  3641. resolve();
  3642. }).catch((err) => {
  3643. reject(err);
  3644. });
  3645. };
  3646. const timeout = setTimeout(() => {
  3647. rejectStep8(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  3648. }, 120000);
  3649. step8PendingReject = (error) => {
  3650. rejectStep8(error);
  3651. };
  3652. webNavListener = (details) => {
  3653. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  3654. finalizeStep8Callback(callbackUrl);
  3655. };
  3656. webNavCommittedListener = (details) => {
  3657. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  3658. finalizeStep8Callback(callbackUrl);
  3659. };
  3660. step8TabUpdatedListener = (tabId, changeInfo, tab) => {
  3661. const callbackUrl = getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId);
  3662. finalizeStep8Callback(callbackUrl);
  3663. };
  3664. (async () => {
  3665. try {
  3666. throwIfStep8SettledOrStopped(resolved);
  3667. signupTabId = await getTabId('signup-page');
  3668. throwIfStep8SettledOrStopped(resolved);
  3669. if (signupTabId && await isTabAlive('signup-page')) {
  3670. await chrome.tabs.update(signupTabId, { active: true });
  3671. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  3672. } else {
  3673. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  3674. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  3675. }
  3676. throwIfStep8SettledOrStopped(resolved);
  3677. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  3678. chrome.webNavigation.onCommitted.addListener(webNavCommittedListener);
  3679. chrome.tabs.onUpdated.addListener(step8TabUpdatedListener);
  3680. await ensureStep8SignupPageReady(signupTabId, {
  3681. timeoutMs: 15000,
  3682. logMessage: '步骤 8:认证页内容脚本尚未就绪,正在等待页面恢复...',
  3683. });
  3684. for (let round = 1; round <= STEP8_MAX_ROUNDS && !resolved; round++) {
  3685. throwIfStep8SettledOrStopped(resolved);
  3686. const pageState = await waitForStep8Ready(signupTabId);
  3687. if (!pageState?.consentReady) {
  3688. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  3689. continue;
  3690. }
  3691. const strategy = STEP8_STRATEGIES[Math.min(round - 1, STEP8_STRATEGIES.length - 1)];
  3692. await addLog(`步骤 8:第 ${round}/${STEP8_MAX_ROUNDS} 轮尝试点击“继续”(${strategy.label})...`);
  3693. if (strategy.mode === 'debugger') {
  3694. const clickTarget = await prepareStep8DebuggerClick(signupTabId);
  3695. throwIfStep8SettledOrStopped(resolved);
  3696. await clickWithDebugger(signupTabId, clickTarget?.rect);
  3697. } else {
  3698. await triggerStep8ContentStrategy(signupTabId, strategy.strategy);
  3699. }
  3700. if (resolved) {
  3701. return;
  3702. }
  3703. const effect = await waitForStep8ClickEffect(signupTabId, pageState.url);
  3704. if (resolved) {
  3705. return;
  3706. }
  3707. if (effect.progressed) {
  3708. await addLog(`步骤 8:检测到本次点击已生效,${getStep8EffectLabel(effect)},继续等待 localhost 回调...`, 'info');
  3709. break;
  3710. }
  3711. if (round >= STEP8_MAX_ROUNDS) {
  3712. throw new Error(`步骤 8:连续 ${STEP8_MAX_ROUNDS} 轮点击“继续”后页面仍无反应。`);
  3713. }
  3714. await addLog(`步骤 8:${strategy.label} 本轮点击后页面无反应,正在刷新认证页后重试(下一轮 ${round + 1}/${STEP8_MAX_ROUNDS})...`, 'warn');
  3715. await reloadStep8ConsentPage(signupTabId);
  3716. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  3717. }
  3718. } catch (err) {
  3719. rejectStep8(err);
  3720. }
  3721. })();
  3722. });
  3723. }
  3724. // ============================================================
  3725. // Step 9: CPA 回调验证(通过 vps-panel.js)
  3726. // ============================================================
  3727. async function executeStep9(state) {
  3728. if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
  3729. throw new Error('步骤 8 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 8。');
  3730. }
  3731. if (!state.localhostUrl) {
  3732. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  3733. }
  3734. if (!state.vpsUrl) {
  3735. throw new Error('尚未填写 CPA 地址,请先在侧边栏输入。');
  3736. }
  3737. if (shouldBypassStep9ForLocalCpa(state)) {
  3738. await addLog('步骤 9:检测到本地 CPA,步骤 8 完成后已自动添加,无需重复提交回调地址。', 'info');
  3739. await completeStepFromBackground(9, {
  3740. localhostUrl: state.localhostUrl,
  3741. verifiedStatus: 'local-auto',
  3742. });
  3743. return;
  3744. }
  3745. await addLog('步骤 9:正在打开 CPA 面板...');
  3746. const injectFiles = ['content/activation-utils.js', 'content/utils.js', 'content/vps-panel.js'];
  3747. let tabId = await getTabId('vps-panel');
  3748. const alive = tabId && await isTabAlive('vps-panel');
  3749. if (!alive) {
  3750. tabId = await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  3751. inject: injectFiles,
  3752. reloadIfSameUrl: true,
  3753. });
  3754. } else {
  3755. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  3756. await chrome.tabs.update(tabId, { active: true });
  3757. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  3758. }
  3759. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  3760. inject: injectFiles,
  3761. timeoutMs: 45000,
  3762. retryDelayMs: 900,
  3763. logMessage: '姝ラ 9锛欳PA 闈㈡澘浠嶅湪鍔犺浇锛屾鍦ㄩ噸璇曡繛鎺ュ唴瀹硅剼鏈?..',
  3764. });
  3765. await addLog('步骤 9:正在填写回调地址...');
  3766. const result = await sendToContentScriptResilient('vps-panel', {
  3767. type: 'EXECUTE_STEP',
  3768. step: 9,
  3769. source: 'background',
  3770. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  3771. }, {
  3772. timeoutMs: 30000,
  3773. retryDelayMs: 700,
  3774. logMessage: '步骤 9:CPA 面板通信未就绪,正在等待页面恢复...',
  3775. });
  3776. if (result?.error) {
  3777. throw new Error(result.error);
  3778. }
  3779. }
  3780. // ============================================================
  3781. // Open Side Panel on extension icon click
  3782. // ============================================================
  3783. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
  3784. chrome.alarms.onAlarm.addListener((alarm) => {
  3785. if (alarm.name !== AUTO_RUN_ALARM_NAME) {
  3786. return;
  3787. }
  3788. launchScheduledAutoRun('alarm').catch((err) => {
  3789. console.error(LOG_PREFIX, 'Failed to launch scheduled auto run from alarm:', err);
  3790. });
  3791. });
  3792. chrome.runtime.onStartup.addListener(() => {
  3793. restoreScheduledAutoRunIfNeeded().catch((err) => {
  3794. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on startup:', err);
  3795. });
  3796. });
  3797. chrome.runtime.onInstalled.addListener(() => {
  3798. restoreScheduledAutoRunIfNeeded().catch((err) => {
  3799. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on install/update:', err);
  3800. });
  3801. });
  3802. restoreScheduledAutoRunIfNeeded().catch((err) => {
  3803. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run:', err);
  3804. });