background.js 211 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294
  1. // background.js — Service Worker: orchestration, state, tab management, message routing
  2. importScripts('data/names.js', 'hotmail-utils.js', 'cloudflare-temp-email-utils.js', 'content/activation-utils.js');
  3. const {
  4. buildHotmailMailApiLatestUrl,
  5. extractVerificationCodeFromMessage,
  6. filterHotmailAccountsByUsage,
  7. getLatestHotmailMessage,
  8. getHotmailMailApiRequestConfig,
  9. getHotmailVerificationPollConfig,
  10. getHotmailVerificationRequestTimestamp,
  11. normalizeHotmailMailApiMessages,
  12. pickHotmailAccountForRun,
  13. pickVerificationMessage,
  14. pickVerificationMessageWithFallback,
  15. pickVerificationMessageWithTimeFallback,
  16. shouldClearHotmailCurrentSelection,
  17. } = self.HotmailUtils;
  18. const {
  19. DEFAULT_MAIL_PAGE_SIZE: CLOUDFLARE_TEMP_EMAIL_DEFAULT_PAGE_SIZE,
  20. buildCloudflareTempEmailHeaders,
  21. getCloudflareTempEmailAddressFromResponse,
  22. joinCloudflareTempEmailUrl,
  23. normalizeCloudflareTempEmailAddress,
  24. normalizeCloudflareTempEmailBaseUrl,
  25. normalizeCloudflareTempEmailDomain,
  26. normalizeCloudflareTempEmailDomains,
  27. normalizeCloudflareTempEmailMailApiMessages,
  28. } = self.CloudflareTempEmailUtils;
  29. const {
  30. isRecoverableStep9AuthFailure,
  31. } = self.MultiPageActivationUtils;
  32. const LOG_PREFIX = '[MultiPage:bg]';
  33. const DUCK_AUTOFILL_URL = 'https://duckduckgo.com/email/settings/autofill';
  34. const HOTMAIL_PROVIDER = 'hotmail-api';
  35. const CLOUDFLARE_TEMP_EMAIL_PROVIDER = 'cloudflare-temp-email';
  36. const CLOUDFLARE_TEMP_EMAIL_GENERATOR = 'cloudflare-temp-email';
  37. const HOTMAIL_MAILBOXES = ['INBOX', 'Junk'];
  38. const STOP_ERROR_MESSAGE = '流程已被用户停止。';
  39. const HUMAN_STEP_DELAY_MIN = 700;
  40. const HUMAN_STEP_DELAY_MAX = 2200;
  41. const STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS = 8;
  42. const SUB2API_STEP1_RESPONSE_TIMEOUT_MS = 90000;
  43. const SUB2API_STEP9_RESPONSE_TIMEOUT_MS = 120000;
  44. const DEFAULT_SUB2API_URL = 'https://sub2api.hisence.fun/admin/accounts';
  45. const DEFAULT_SUB2API_GROUP_NAME = 'codex';
  46. const DEFAULT_SUB2API_REDIRECT_URI = 'http://localhost:1455/auth/callback';
  47. const AUTO_RUN_ALARM_NAME = 'scheduled-auto-run';
  48. const AUTO_RUN_DELAY_MIN_MINUTES = 1;
  49. const AUTO_RUN_DELAY_MAX_MINUTES = 1440;
  50. const AUTO_RUN_RETRY_DELAY_MS = 3000;
  51. const AUTO_RUN_MAX_RETRIES_PER_ROUND = 3;
  52. const AUTO_STEP_DELAY_MIN_ALLOWED_SECONDS = 0;
  53. const AUTO_STEP_DELAY_MAX_ALLOWED_SECONDS = 600;
  54. const LEGACY_AUTO_STEP_DELAY_KEYS = ['autoStepRandomDelayMinSeconds', 'autoStepRandomDelayMaxSeconds'];
  55. const DEFAULT_LOCAL_CPA_STEP9_MODE = 'submit';
  56. const HOTMAIL_SERVICE_MODE_REMOTE = 'remote';
  57. const HOTMAIL_SERVICE_MODE_LOCAL = 'local';
  58. const DEFAULT_HOTMAIL_REMOTE_BASE_URL = '';
  59. const DEFAULT_HOTMAIL_LOCAL_BASE_URL = 'http://127.0.0.1:17373';
  60. const HOTMAIL_LOCAL_HELPER_TIMEOUT_MS = 45000;
  61. const DISPLAY_TIMEZONE = 'Asia/Shanghai';
  62. initializeSessionStorageAccess();
  63. // ============================================================
  64. // 状态管理(chrome.storage.session + chrome.storage.local)
  65. // ============================================================
  66. const PERSISTED_SETTING_DEFAULTS = {
  67. panelMode: 'cpa',
  68. vpsUrl: '',
  69. vpsPassword: '',
  70. localCpaStep9Mode: DEFAULT_LOCAL_CPA_STEP9_MODE,
  71. sub2apiUrl: DEFAULT_SUB2API_URL,
  72. sub2apiEmail: '',
  73. sub2apiPassword: '',
  74. sub2apiGroupName: DEFAULT_SUB2API_GROUP_NAME,
  75. customPassword: '',
  76. autoRunSkipFailures: false,
  77. autoRunFallbackThreadIntervalMinutes: 0,
  78. autoRunDelayEnabled: false,
  79. autoRunDelayMinutes: 30,
  80. autoStepDelaySeconds: null,
  81. mailProvider: '163',
  82. emailGenerator: 'duck',
  83. emailPrefix: '',
  84. inbucketHost: '',
  85. inbucketMailbox: '',
  86. hotmailServiceMode: HOTMAIL_SERVICE_MODE_LOCAL,
  87. hotmailRemoteBaseUrl: DEFAULT_HOTMAIL_REMOTE_BASE_URL,
  88. hotmailLocalBaseUrl: DEFAULT_HOTMAIL_LOCAL_BASE_URL,
  89. cloudflareDomain: '',
  90. cloudflareDomains: [],
  91. cloudflareTempEmailBaseUrl: '',
  92. cloudflareTempEmailAdminAuth: '',
  93. cloudflareTempEmailCustomAuth: '',
  94. cloudflareTempEmailDomain: '',
  95. cloudflareTempEmailDomains: [],
  96. hotmailAccounts: [],
  97. };
  98. const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);
  99. const SETTINGS_EXPORT_SCHEMA_VERSION = 1;
  100. const SETTINGS_EXPORT_FILENAME_PREFIX = 'multipage-settings';
  101. const DEFAULT_STATE = {
  102. currentStep: 0, // 当前流程执行到的步骤编号。
  103. stepStatuses: {
  104. 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending', // 运行时步骤状态映射,不要手动预填。
  105. 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
  106. },
  107. oauthUrl: null, // 运行时抓取到的 OAuth 地址,不要手动预填。
  108. email: null, // 运行时邮箱,由程序自动获取并写入,不能手动预填。
  109. password: null, // 运行时实际密码,由 customPassword 或程序自动生成后写入。
  110. accounts: [], // 已生成账号记录:{ email, password, createdAt }。
  111. lastEmailTimestamp: null, // 最近一次获取到邮箱数据的运行时时间戳。
  112. lastSignupCode: null, // 注册验证码,运行时由程序自动读取并写入。
  113. lastLoginCode: null, // 登录验证码,运行时由程序自动读取并写入。
  114. localhostUrl: null, // 运行时捕获到的 localhost 回调地址,不要手动预填。
  115. sub2apiSessionId: null, // SUB2API OpenAI Auth 会话 ID。
  116. sub2apiOAuthState: null, // SUB2API OpenAI Auth state。
  117. sub2apiGroupId: null, // SUB2API 目标分组 ID。
  118. sub2apiDraftName: null, // SUB2API 本轮预生成的账号名称。
  119. flowStartTime: null, // 当前流程开始时间。
  120. tabRegistry: {}, // 程序维护的标签页注册表。
  121. sourceLastUrls: {}, // 各来源页面最近一次打开的地址记录。
  122. logs: [], // 侧边栏展示的运行日志。
  123. ...PERSISTED_SETTING_DEFAULTS, // 合并 chrome.storage.local 中持久化保存的用户配置。
  124. autoRunning: false, // 当前是否处于自动运行中。
  125. autoRunPhase: 'idle', // 当前自动运行阶段。
  126. autoRunCurrentRun: 0, // 自动运行当前执行到第几轮。
  127. autoRunTotalRuns: 1, // 自动运行计划总轮数。
  128. autoRunAttemptRun: 0, // 当前轮次的重试序号。
  129. autoRunRoundSummaries: [], // 自动运行轮次摘要。
  130. scheduledAutoRunAt: null, // 自动运行计划启动时间戳。
  131. scheduledAutoRunPlan: null, // 自动运行计划参数快照。
  132. autoRunCountdownAt: null,
  133. autoRunCountdownTitle: '',
  134. autoRunCountdownNote: '',
  135. signupVerificationRequestedAt: null,
  136. loginVerificationRequestedAt: null,
  137. currentHotmailAccountId: null,
  138. };
  139. function normalizeAutoRunDelayMinutes(value) {
  140. const numeric = Number(value);
  141. if (!Number.isFinite(numeric)) {
  142. return PERSISTED_SETTING_DEFAULTS.autoRunDelayMinutes;
  143. }
  144. return Math.min(
  145. AUTO_RUN_DELAY_MAX_MINUTES,
  146. Math.max(AUTO_RUN_DELAY_MIN_MINUTES, Math.floor(numeric))
  147. );
  148. }
  149. function normalizeAutoRunFallbackThreadIntervalMinutes(value) {
  150. const rawValue = String(value ?? '').trim();
  151. if (!rawValue) {
  152. return 0;
  153. }
  154. const numeric = Number(rawValue);
  155. if (!Number.isFinite(numeric)) {
  156. return 0;
  157. }
  158. return Math.min(
  159. AUTO_RUN_DELAY_MAX_MINUTES,
  160. Math.max(0, Math.floor(numeric))
  161. );
  162. }
  163. function normalizeAutoStepDelaySeconds(value, fallback = null) {
  164. const rawValue = String(value ?? '').trim();
  165. if (!rawValue) {
  166. return fallback;
  167. }
  168. const numeric = Number(rawValue);
  169. if (!Number.isFinite(numeric)) {
  170. return fallback;
  171. }
  172. return Math.min(
  173. AUTO_STEP_DELAY_MAX_ALLOWED_SECONDS,
  174. Math.max(AUTO_STEP_DELAY_MIN_ALLOWED_SECONDS, Math.floor(numeric))
  175. );
  176. }
  177. function resolveLegacyAutoStepDelaySeconds(input = {}) {
  178. const hasLegacyMin = input.autoStepRandomDelayMinSeconds !== undefined;
  179. const hasLegacyMax = input.autoStepRandomDelayMaxSeconds !== undefined;
  180. if (!hasLegacyMin && !hasLegacyMax) {
  181. return undefined;
  182. }
  183. const minSeconds = normalizeAutoStepDelaySeconds(input.autoStepRandomDelayMinSeconds, null);
  184. const maxSeconds = normalizeAutoStepDelaySeconds(input.autoStepRandomDelayMaxSeconds, null);
  185. if (minSeconds === null && maxSeconds === null) {
  186. return null;
  187. }
  188. if (minSeconds === null) {
  189. return maxSeconds;
  190. }
  191. if (maxSeconds === null) {
  192. return minSeconds;
  193. }
  194. return Math.round((minSeconds + maxSeconds) / 2);
  195. }
  196. function normalizeRunCount(value) {
  197. const numeric = Number(value);
  198. if (!Number.isFinite(numeric)) {
  199. return 1;
  200. }
  201. return Math.min(50, Math.max(1, Math.floor(numeric)));
  202. }
  203. function normalizeScheduledAutoRunPlan(plan) {
  204. if (!plan || typeof plan !== 'object') {
  205. return null;
  206. }
  207. return {
  208. totalRuns: normalizeRunCount(plan.totalRuns),
  209. autoRunSkipFailures: Boolean(plan.autoRunSkipFailures),
  210. mode: plan.mode === 'continue' ? 'continue' : 'restart',
  211. };
  212. }
  213. function normalizeEmailGenerator(value = '') {
  214. const normalized = String(value || '').trim().toLowerCase();
  215. if (normalized === 'custom' || normalized === 'manual') {
  216. return 'custom';
  217. }
  218. if (normalized === 'cloudflare') return 'cloudflare';
  219. if (normalized === CLOUDFLARE_TEMP_EMAIL_GENERATOR) return CLOUDFLARE_TEMP_EMAIL_GENERATOR;
  220. return 'duck';
  221. }
  222. function normalizePanelMode(value = '') {
  223. return String(value || '').trim().toLowerCase() === 'sub2api' ? 'sub2api' : 'cpa';
  224. }
  225. function normalizeMailProvider(value = '') {
  226. const normalized = String(value || '').trim().toLowerCase();
  227. switch (normalized) {
  228. case 'custom':
  229. case HOTMAIL_PROVIDER:
  230. case CLOUDFLARE_TEMP_EMAIL_PROVIDER:
  231. case '163':
  232. case '163-vip':
  233. case 'qq':
  234. case 'inbucket':
  235. case '2925':
  236. return normalized;
  237. default:
  238. return PERSISTED_SETTING_DEFAULTS.mailProvider;
  239. }
  240. }
  241. function normalizeLocalCpaStep9Mode(value = '') {
  242. return String(value || '').trim().toLowerCase() === 'bypass'
  243. ? 'bypass'
  244. : DEFAULT_LOCAL_CPA_STEP9_MODE;
  245. }
  246. function normalizeCloudflareDomain(rawValue = '') {
  247. let value = String(rawValue || '').trim().toLowerCase();
  248. if (!value) return '';
  249. value = value.replace(/^@+/, '');
  250. value = value.replace(/^https?:\/\//, '');
  251. value = value.replace(/\/.*$/, '');
  252. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(value)) return '';
  253. return value;
  254. }
  255. function normalizeCloudflareDomains(values) {
  256. const normalizedDomains = [];
  257. const seen = new Set();
  258. for (const value of Array.isArray(values) ? values : []) {
  259. const normalized = normalizeCloudflareDomain(value);
  260. if (!normalized || seen.has(normalized)) continue;
  261. seen.add(normalized);
  262. normalizedDomains.push(normalized);
  263. }
  264. return normalizedDomains;
  265. }
  266. function normalizeHotmailServiceMode(rawValue = '') {
  267. return HOTMAIL_SERVICE_MODE_LOCAL;
  268. }
  269. function normalizeHotmailRemoteBaseUrl(rawValue = '') {
  270. const value = String(rawValue || '').trim();
  271. if (!value) return DEFAULT_HOTMAIL_REMOTE_BASE_URL;
  272. try {
  273. const parsed = new URL(value);
  274. if (!['http:', 'https:'].includes(parsed.protocol)) {
  275. return DEFAULT_HOTMAIL_REMOTE_BASE_URL;
  276. }
  277. if (parsed.pathname.endsWith('/api/mail-new') || parsed.pathname.endsWith('/api/mail-all') || parsed.pathname === '/api.html') {
  278. parsed.pathname = '';
  279. parsed.search = '';
  280. parsed.hash = '';
  281. }
  282. return parsed.toString().replace(/\/$/, '');
  283. } catch {
  284. return DEFAULT_HOTMAIL_REMOTE_BASE_URL;
  285. }
  286. }
  287. function normalizeHotmailLocalBaseUrl(rawValue = '') {
  288. const value = String(rawValue || '').trim();
  289. if (!value) return DEFAULT_HOTMAIL_LOCAL_BASE_URL;
  290. try {
  291. const parsed = new URL(value);
  292. if (!['http:', 'https:'].includes(parsed.protocol)) {
  293. return DEFAULT_HOTMAIL_LOCAL_BASE_URL;
  294. }
  295. if (['/messages', '/code', '/clear', '/token'].includes(parsed.pathname)) {
  296. parsed.pathname = '';
  297. parsed.search = '';
  298. parsed.hash = '';
  299. }
  300. return parsed.toString().replace(/\/$/, '');
  301. } catch {
  302. return DEFAULT_HOTMAIL_LOCAL_BASE_URL;
  303. }
  304. }
  305. function getHotmailServiceSettings(state = {}) {
  306. return {
  307. mode: normalizeHotmailServiceMode(state.hotmailServiceMode),
  308. remoteBaseUrl: normalizeHotmailRemoteBaseUrl(state.hotmailRemoteBaseUrl),
  309. localBaseUrl: normalizeHotmailLocalBaseUrl(state.hotmailLocalBaseUrl),
  310. };
  311. }
  312. function getCloudflareTempEmailConfig(state = {}) {
  313. return {
  314. baseUrl: normalizeCloudflareTempEmailBaseUrl(state.cloudflareTempEmailBaseUrl),
  315. adminAuth: String(state.cloudflareTempEmailAdminAuth || ''),
  316. customAuth: String(state.cloudflareTempEmailCustomAuth || ''),
  317. domain: normalizeCloudflareTempEmailDomain(state.cloudflareTempEmailDomain),
  318. domains: normalizeCloudflareTempEmailDomains(state.cloudflareTempEmailDomains),
  319. };
  320. }
  321. function normalizePersistentSettingValue(key, value) {
  322. switch (key) {
  323. case 'panelMode':
  324. return normalizePanelMode(value);
  325. case 'vpsUrl':
  326. return String(value || '').trim();
  327. case 'vpsPassword':
  328. return String(value || '');
  329. case 'localCpaStep9Mode':
  330. return normalizeLocalCpaStep9Mode(value);
  331. case 'sub2apiUrl':
  332. return String(value || '').trim();
  333. case 'sub2apiEmail':
  334. return String(value || '').trim();
  335. case 'sub2apiPassword':
  336. return String(value || '');
  337. case 'sub2apiGroupName':
  338. return String(value || '').trim();
  339. case 'customPassword':
  340. return String(value || '');
  341. case 'autoRunSkipFailures':
  342. case 'autoRunDelayEnabled':
  343. return Boolean(value);
  344. case 'autoRunFallbackThreadIntervalMinutes':
  345. return normalizeAutoRunFallbackThreadIntervalMinutes(value);
  346. case 'autoRunDelayMinutes':
  347. return normalizeAutoRunDelayMinutes(value);
  348. case 'autoStepDelaySeconds':
  349. return normalizeAutoStepDelaySeconds(value, PERSISTED_SETTING_DEFAULTS.autoStepDelaySeconds);
  350. case 'mailProvider':
  351. return normalizeMailProvider(value);
  352. case 'emailGenerator':
  353. return normalizeEmailGenerator(value);
  354. case 'emailPrefix':
  355. return String(value || '').trim();
  356. case 'inbucketHost':
  357. return String(value || '').trim();
  358. case 'inbucketMailbox':
  359. return String(value || '').trim();
  360. case 'hotmailServiceMode':
  361. return normalizeHotmailServiceMode(value);
  362. case 'hotmailRemoteBaseUrl':
  363. return normalizeHotmailRemoteBaseUrl(value);
  364. case 'hotmailLocalBaseUrl':
  365. return normalizeHotmailLocalBaseUrl(value);
  366. case 'cloudflareDomain':
  367. return normalizeCloudflareDomain(value);
  368. case 'cloudflareDomains':
  369. return normalizeCloudflareDomains(value);
  370. case 'cloudflareTempEmailBaseUrl':
  371. return normalizeCloudflareTempEmailBaseUrl(value);
  372. case 'cloudflareTempEmailAdminAuth':
  373. case 'cloudflareTempEmailCustomAuth':
  374. return String(value || '');
  375. case 'cloudflareTempEmailDomain':
  376. return normalizeCloudflareTempEmailDomain(value);
  377. case 'cloudflareTempEmailDomains':
  378. return normalizeCloudflareTempEmailDomains(value);
  379. case 'hotmailAccounts':
  380. return normalizeHotmailAccounts(value);
  381. default:
  382. return value;
  383. }
  384. }
  385. function buildPersistentSettingsPayload(input = {}, options = {}) {
  386. const { fillDefaults = false, requireKnownKeys = false } = options;
  387. if (!input || typeof input !== 'object' || Array.isArray(input)) {
  388. throw new Error('\u914d\u7f6e\u5185\u5bb9\u683c\u5f0f\u65e0\u6548\u3002');
  389. }
  390. const normalizedInput = { ...input };
  391. if (normalizedInput.autoStepDelaySeconds === undefined) {
  392. const legacyAutoStepDelaySeconds = resolveLegacyAutoStepDelaySeconds(normalizedInput);
  393. if (legacyAutoStepDelaySeconds !== undefined) {
  394. normalizedInput.autoStepDelaySeconds = legacyAutoStepDelaySeconds;
  395. }
  396. }
  397. const payload = {};
  398. let matchedKeyCount = 0;
  399. for (const key of PERSISTED_SETTING_KEYS) {
  400. if (normalizedInput[key] !== undefined) {
  401. payload[key] = normalizePersistentSettingValue(key, normalizedInput[key]);
  402. matchedKeyCount += 1;
  403. } else if (fillDefaults) {
  404. payload[key] = normalizePersistentSettingValue(key, PERSISTED_SETTING_DEFAULTS[key]);
  405. }
  406. }
  407. if (requireKnownKeys && matchedKeyCount === 0) {
  408. throw new Error('\u914d\u7f6e\u6587\u4ef6\u4e2d\u6ca1\u6709\u53ef\u8bc6\u522b\u7684\u914d\u7f6e\u5185\u5bb9\u3002');
  409. }
  410. if (payload.cloudflareDomains) {
  411. const domains = normalizeCloudflareDomains(payload.cloudflareDomains);
  412. if (payload.cloudflareDomain && !domains.includes(payload.cloudflareDomain)) {
  413. domains.unshift(payload.cloudflareDomain);
  414. }
  415. payload.cloudflareDomains = domains;
  416. }
  417. if (payload.cloudflareTempEmailDomains) {
  418. const domains = normalizeCloudflareTempEmailDomains(payload.cloudflareTempEmailDomains);
  419. if (payload.cloudflareTempEmailDomain && !domains.includes(payload.cloudflareTempEmailDomain)) {
  420. domains.unshift(payload.cloudflareTempEmailDomain);
  421. }
  422. payload.cloudflareTempEmailDomains = domains;
  423. }
  424. return payload;
  425. }
  426. async function getPersistedSettings() {
  427. const stored = await chrome.storage.local.get([...PERSISTED_SETTING_KEYS, ...LEGACY_AUTO_STEP_DELAY_KEYS]);
  428. return buildPersistentSettingsPayload(stored, { fillDefaults: true });
  429. }
  430. async function getState() {
  431. const [state, persistedSettings] = await Promise.all([
  432. chrome.storage.session.get(null),
  433. getPersistedSettings(),
  434. ]);
  435. return { ...DEFAULT_STATE, ...persistedSettings, ...state };
  436. }
  437. async function initializeSessionStorageAccess() {
  438. try {
  439. if (chrome.storage?.session?.setAccessLevel) {
  440. await chrome.storage.session.setAccessLevel({
  441. accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS',
  442. });
  443. console.log(LOG_PREFIX, 'Enabled storage.session for content scripts');
  444. }
  445. } catch (err) {
  446. console.warn(LOG_PREFIX, 'Failed to enable storage.session for content scripts:', err?.message || err);
  447. }
  448. }
  449. async function setState(updates) {
  450. console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
  451. if (Object.keys(updates || {}).length > 0) {
  452. await chrome.storage.session.set(updates);
  453. }
  454. }
  455. async function setPersistentSettings(updates) {
  456. const persistedUpdates = buildPersistentSettingsPayload(updates);
  457. if (Object.keys(persistedUpdates).length > 0) {
  458. await chrome.storage.local.set(persistedUpdates);
  459. }
  460. }
  461. function buildSettingsExportFilename(date = new Date()) {
  462. const pad = (value) => String(value).padStart(2, '0');
  463. return `${SETTINGS_EXPORT_FILENAME_PREFIX}-${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}.json`;
  464. }
  465. async function exportSettingsBundle() {
  466. const settings = await getPersistedSettings();
  467. const bundle = {
  468. schemaVersion: SETTINGS_EXPORT_SCHEMA_VERSION,
  469. exportedAt: new Date().toISOString(),
  470. extensionVersion: chrome.runtime.getManifest().version,
  471. settings,
  472. };
  473. return {
  474. fileName: buildSettingsExportFilename(),
  475. fileContent: JSON.stringify(bundle, null, 2),
  476. };
  477. }
  478. async function importSettingsBundle(configBundle) {
  479. const state = await ensureManualInteractionAllowed('\u5bfc\u5165\u914d\u7f6e');
  480. if (Object.values(state.stepStatuses || {}).some((status) => status === 'running')) {
  481. throw new Error('\u5f53\u524d\u6709\u6b65\u9aa4\u6b63\u5728\u6267\u884c\uff0c\u65e0\u6cd5\u5bfc\u5165\u914d\u7f6e\u3002');
  482. }
  483. if (!configBundle || typeof configBundle !== 'object' || Array.isArray(configBundle)) {
  484. throw new Error('\u914d\u7f6e\u6587\u4ef6\u5185\u5bb9\u65e0\u6548\u3002');
  485. }
  486. const schemaVersion = Number(configBundle.schemaVersion);
  487. if (schemaVersion !== SETTINGS_EXPORT_SCHEMA_VERSION) {
  488. throw new Error(`\u4ec5\u652f\u6301\u5bfc\u5165 schemaVersion=${SETTINGS_EXPORT_SCHEMA_VERSION} \u7684\u914d\u7f6e\u6587\u4ef6\u3002`);
  489. }
  490. if (!configBundle.settings || typeof configBundle.settings !== 'object' || Array.isArray(configBundle.settings)) {
  491. throw new Error('\u914d\u7f6e\u6587\u4ef6\u7f3a\u5c11 settings \u914d\u7f6e\u6bb5\u3002');
  492. }
  493. const importedSettings = buildPersistentSettingsPayload(configBundle.settings, {
  494. fillDefaults: true,
  495. requireKnownKeys: true,
  496. });
  497. await setPersistentSettings(importedSettings);
  498. const sessionUpdates = {
  499. ...importedSettings,
  500. currentHotmailAccountId: null,
  501. email: null,
  502. };
  503. await setState(sessionUpdates);
  504. broadcastDataUpdate({
  505. ...importedSettings,
  506. currentHotmailAccountId: null,
  507. ...(sessionUpdates.email !== undefined ? { email: sessionUpdates.email } : {}),
  508. });
  509. return getState();
  510. }
  511. function broadcastDataUpdate(payload) {
  512. chrome.runtime.sendMessage({
  513. type: 'DATA_UPDATED',
  514. payload,
  515. }).catch(() => { });
  516. }
  517. async function setEmailStateSilently(email) {
  518. await setState({ email });
  519. broadcastDataUpdate({ email });
  520. }
  521. async function setEmailState(email) {
  522. await setEmailStateSilently(email);
  523. if (email) {
  524. await resumeAutoRunIfWaitingForEmail();
  525. }
  526. }
  527. async function setPasswordState(password) {
  528. await setState({ password });
  529. broadcastDataUpdate({ password });
  530. }
  531. async function resetState() {
  532. console.log(LOG_PREFIX, 'Resetting all state');
  533. // Preserve settings and persistent data across resets
  534. const [prev, persistedSettings] = await Promise.all([
  535. chrome.storage.session.get([
  536. 'seenCodes',
  537. 'seenInbucketMailIds',
  538. 'accounts',
  539. 'tabRegistry',
  540. 'sourceLastUrls',
  541. ]),
  542. getPersistedSettings(),
  543. ]);
  544. await chrome.storage.session.clear();
  545. await chrome.storage.session.set({
  546. ...DEFAULT_STATE,
  547. ...persistedSettings,
  548. seenCodes: prev.seenCodes || [],
  549. seenInbucketMailIds: prev.seenInbucketMailIds || [],
  550. accounts: prev.accounts || [],
  551. tabRegistry: prev.tabRegistry || {},
  552. sourceLastUrls: prev.sourceLastUrls || {},
  553. });
  554. }
  555. /**
  556. * Generate a random password: 14 chars, mix of uppercase, lowercase, digits, symbols.
  557. */
  558. function generatePassword() {
  559. const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  560. const lower = 'abcdefghjkmnpqrstuvwxyz';
  561. const digits = '23456789';
  562. const symbols = '!@#$%&*?';
  563. const all = upper + lower + digits + symbols;
  564. // Ensure at least one of each type
  565. let pw = '';
  566. pw += upper[Math.floor(Math.random() * upper.length)];
  567. pw += lower[Math.floor(Math.random() * lower.length)];
  568. pw += digits[Math.floor(Math.random() * digits.length)];
  569. pw += symbols[Math.floor(Math.random() * symbols.length)];
  570. // Fill remaining 10 chars
  571. for (let i = 0; i < 10; i++) {
  572. pw += all[Math.floor(Math.random() * all.length)];
  573. }
  574. // Shuffle
  575. return pw.split('').sort(() => Math.random() - 0.5).join('');
  576. }
  577. function normalizeHotmailAccount(account = {}) {
  578. const normalizedLastAuthAt = Number.isFinite(Number(account.lastAuthAt)) ? Number(account.lastAuthAt) : 0;
  579. const normalizedStatus = String(
  580. account.status
  581. || (normalizedLastAuthAt > 0 ? 'authorized' : 'pending')
  582. );
  583. return {
  584. id: String(account.id || crypto.randomUUID()),
  585. email: String(account.email || '').trim(),
  586. password: String(account.password || ''),
  587. clientId: String(account.clientId || '').trim(),
  588. refreshToken: String(account.refreshToken || ''),
  589. status: normalizedStatus,
  590. enabled: account.enabled !== undefined ? Boolean(account.enabled) : true,
  591. used: Boolean(account.used),
  592. lastUsedAt: Number.isFinite(Number(account.lastUsedAt)) ? Number(account.lastUsedAt) : 0,
  593. lastAuthAt: normalizedLastAuthAt,
  594. lastError: String(account.lastError || ''),
  595. };
  596. }
  597. function normalizeHotmailAccounts(accounts) {
  598. if (!Array.isArray(accounts)) return [];
  599. const deduped = new Map();
  600. for (const account of accounts) {
  601. const normalized = normalizeHotmailAccount(account);
  602. if (!normalized.email && !normalized.id) continue;
  603. deduped.set(normalized.id, normalized);
  604. }
  605. return [...deduped.values()];
  606. }
  607. function findHotmailAccount(accounts, accountId) {
  608. return normalizeHotmailAccounts(accounts).find((account) => account.id === accountId) || null;
  609. }
  610. function isHotmailProvider(stateOrProvider) {
  611. const provider = typeof stateOrProvider === 'string'
  612. ? stateOrProvider
  613. : stateOrProvider?.mailProvider;
  614. return provider === HOTMAIL_PROVIDER;
  615. }
  616. function isCustomMailProvider(stateOrProvider) {
  617. const provider = typeof stateOrProvider === 'string'
  618. ? stateOrProvider
  619. : stateOrProvider?.mailProvider;
  620. return provider === 'custom';
  621. }
  622. async function syncHotmailAccounts(accounts) {
  623. const normalized = normalizeHotmailAccounts(accounts);
  624. await setPersistentSettings({ hotmailAccounts: normalized });
  625. await setState({ hotmailAccounts: normalized });
  626. broadcastDataUpdate({ hotmailAccounts: normalized });
  627. return normalized;
  628. }
  629. async function upsertHotmailAccount(input) {
  630. const state = await getState();
  631. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  632. const normalizedEmail = String(input?.email || '').trim().toLowerCase();
  633. const existing = input?.id
  634. ? findHotmailAccount(accounts, input.id)
  635. : accounts.find((account) => account.email.toLowerCase() === normalizedEmail) || null;
  636. const credentialsChanged = !existing
  637. || (input?.clientId !== undefined && String(input.clientId).trim() !== existing.clientId)
  638. || (input?.refreshToken !== undefined && String(input.refreshToken).trim() !== existing.refreshToken)
  639. || (input?.email !== undefined && String(input.email).trim().toLowerCase() !== existing.email.toLowerCase());
  640. const normalized = normalizeHotmailAccount({
  641. ...(existing || {}),
  642. ...(credentialsChanged ? {
  643. status: 'pending',
  644. lastAuthAt: 0,
  645. lastError: '',
  646. } : {}),
  647. ...input,
  648. id: input?.id || existing?.id || crypto.randomUUID(),
  649. });
  650. const nextAccounts = existing
  651. ? accounts.map((account) => (account.id === normalized.id ? normalized : account))
  652. : [...accounts, normalized];
  653. await syncHotmailAccounts(nextAccounts);
  654. return normalized;
  655. }
  656. async function deleteHotmailAccount(accountId) {
  657. const state = await getState();
  658. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  659. const nextAccounts = accounts.filter((account) => account.id !== accountId);
  660. await syncHotmailAccounts(nextAccounts);
  661. if (state.currentHotmailAccountId === accountId) {
  662. await setState({ currentHotmailAccountId: null });
  663. if (isHotmailProvider(state)) {
  664. await setEmailState(null);
  665. }
  666. broadcastDataUpdate({ currentHotmailAccountId: null });
  667. }
  668. }
  669. async function deleteHotmailAccounts(mode = 'all') {
  670. const state = await getState();
  671. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  672. const targets = filterHotmailAccountsByUsage(accounts, mode);
  673. const targetIds = new Set(targets.map((account) => account.id));
  674. const nextAccounts = mode === 'used'
  675. ? accounts.filter((account) => !targetIds.has(account.id))
  676. : [];
  677. await syncHotmailAccounts(nextAccounts);
  678. if (state.currentHotmailAccountId && targetIds.has(state.currentHotmailAccountId)) {
  679. await setState({ currentHotmailAccountId: null });
  680. if (isHotmailProvider(state)) {
  681. await setEmailState(null);
  682. }
  683. broadcastDataUpdate({ currentHotmailAccountId: null });
  684. }
  685. return {
  686. deletedCount: targets.length,
  687. remainingCount: nextAccounts.length,
  688. };
  689. }
  690. async function patchHotmailAccount(accountId, updates = {}) {
  691. const state = await getState();
  692. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  693. const account = findHotmailAccount(accounts, accountId);
  694. if (!account) {
  695. throw new Error('未找到对应的 Hotmail 账号。');
  696. }
  697. const nextAccount = normalizeHotmailAccount({
  698. ...account,
  699. ...updates,
  700. id: account.id,
  701. });
  702. await syncHotmailAccounts(accounts.map((item) => (item.id === account.id ? nextAccount : item)));
  703. if (state.currentHotmailAccountId === account.id && shouldClearHotmailCurrentSelection(nextAccount)) {
  704. await setState({ currentHotmailAccountId: null });
  705. broadcastDataUpdate({ currentHotmailAccountId: null });
  706. if (isHotmailProvider(state)) {
  707. await setEmailState(null);
  708. }
  709. }
  710. return nextAccount;
  711. }
  712. async function setCurrentHotmailAccount(accountId, options = {}) {
  713. const { markUsed = false, syncEmail = true } = options;
  714. const state = await getState();
  715. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  716. const account = findHotmailAccount(accounts, accountId);
  717. if (!account) {
  718. throw new Error('未找到对应的 Hotmail 账号。');
  719. }
  720. if (markUsed) {
  721. account.lastUsedAt = Date.now();
  722. await syncHotmailAccounts(accounts.map((item) => (item.id === account.id ? account : item)));
  723. }
  724. await setState({ currentHotmailAccountId: account.id });
  725. broadcastDataUpdate({ currentHotmailAccountId: account.id });
  726. if (syncEmail) {
  727. await setEmailState(account.email || null);
  728. }
  729. return account;
  730. }
  731. async function ensureHotmailAccountForFlow(options = {}) {
  732. const { allowAllocate = true, markUsed = false, preferredAccountId = null } = options;
  733. const state = await getState();
  734. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  735. const isAccountAllocatable = (candidate) => Boolean(candidate)
  736. && candidate.status === 'authorized'
  737. && !candidate.used
  738. && Boolean(candidate.refreshToken);
  739. let account = null;
  740. if (preferredAccountId) {
  741. account = findHotmailAccount(accounts, preferredAccountId);
  742. }
  743. if (!account && state.currentHotmailAccountId) {
  744. account = findHotmailAccount(accounts, state.currentHotmailAccountId);
  745. }
  746. if ((!account || !isAccountAllocatable(account)) && allowAllocate) {
  747. account = pickHotmailAccountForRun(accounts, {});
  748. }
  749. if (!account) {
  750. throw new Error('没有可用的 Hotmail 账号。请先在侧边栏添加至少一个带刷新令牌(refresh token)的账号。');
  751. }
  752. if (!isAccountAllocatable(account)) {
  753. throw new Error(`Hotmail 账号 ${account.email || account.id} 尚未就绪,无法读取邮件。`);
  754. }
  755. return setCurrentHotmailAccount(account.id, { markUsed, syncEmail: true });
  756. }
  757. function buildHotmailRemoteEndpoint(baseUrl, path) {
  758. const normalizedBaseUrl = normalizeHotmailRemoteBaseUrl(baseUrl);
  759. return new URL(path, `${normalizedBaseUrl}/`).toString();
  760. }
  761. function buildHotmailLocalEndpoint(baseUrl, path) {
  762. const normalizedBaseUrl = normalizeHotmailLocalBaseUrl(baseUrl);
  763. return new URL(path, `${normalizedBaseUrl}/`).toString();
  764. }
  765. async function requestHotmailRemoteMailbox(account, mailbox = 'INBOX') {
  766. if (!account?.email) {
  767. throw new Error('Hotmail 账号缺少邮箱地址。');
  768. }
  769. if (!account?.clientId) {
  770. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少客户端 ID。`);
  771. }
  772. if (!account?.refreshToken) {
  773. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少刷新令牌(refresh token)。`);
  774. }
  775. const serviceSettings = getHotmailServiceSettings(await getState());
  776. const url = buildHotmailMailApiLatestUrl({
  777. apiUrl: buildHotmailRemoteEndpoint(serviceSettings.remoteBaseUrl, '/api/mail-new'),
  778. clientId: account.clientId,
  779. email: account.email,
  780. refreshToken: account.refreshToken,
  781. mailbox,
  782. responseType: 'json',
  783. });
  784. const { timeoutMs } = getHotmailMailApiRequestConfig();
  785. const controller = new AbortController();
  786. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
  787. let response;
  788. try {
  789. response = await fetch(url, { method: 'GET', signal: controller.signal });
  790. } catch (err) {
  791. if (err?.name === 'AbortError') {
  792. throw new Error(`Hotmail API 请求超时(>${Math.round(timeoutMs / 1000)} 秒):${mailbox}`);
  793. }
  794. throw new Error(`Hotmail API 请求失败:${err.message}`);
  795. } finally {
  796. clearTimeout(timeoutId);
  797. }
  798. const text = await response.text();
  799. let payload = {};
  800. try {
  801. payload = text ? JSON.parse(text) : {};
  802. } catch {
  803. payload = { raw: text };
  804. }
  805. if (!response.ok) {
  806. const errorText = payload?.message || payload?.error || payload?.msg || text || `HTTP ${response.status}`;
  807. throw new Error(`Hotmail API 请求失败:${errorText}`);
  808. }
  809. if (payload && payload.success === false) {
  810. const errorText = payload?.message || payload?.msg || payload?.error || '未知错误';
  811. throw new Error(`Hotmail API 返回失败:${errorText}`);
  812. }
  813. return {
  814. mailbox,
  815. payload,
  816. messages: normalizeHotmailMailApiMessages(payload?.data),
  817. nextRefreshToken: String(payload?.new_refresh_token || payload?.newRefreshToken || '').trim(),
  818. };
  819. }
  820. function applyHotmailApiResultToAccount(account, apiResult) {
  821. const nextRefreshToken = String(apiResult?.nextRefreshToken || '').trim();
  822. return {
  823. ...account,
  824. refreshToken: nextRefreshToken || account.refreshToken,
  825. status: 'authorized',
  826. lastAuthAt: Date.now(),
  827. lastError: '',
  828. };
  829. }
  830. function buildHotmailMailApiFailureAccount(account, errorMessage) {
  831. return normalizeHotmailAccount({
  832. ...account,
  833. status: 'error',
  834. lastError: String(errorMessage || ''),
  835. });
  836. }
  837. async function fetchHotmailMailboxMessagesFromRemoteService(account, mailboxes = HOTMAIL_MAILBOXES) {
  838. let workingAccount = normalizeHotmailAccount(account);
  839. const mailboxResults = [];
  840. try {
  841. for (const mailbox of mailboxes) {
  842. const result = await requestHotmailRemoteMailbox(workingAccount, mailbox);
  843. workingAccount = applyHotmailApiResultToAccount(workingAccount, result);
  844. mailboxResults.push({
  845. mailbox,
  846. count: result.messages.length,
  847. messages: result.messages.map((message) => ({ ...message, mailbox })),
  848. });
  849. }
  850. } catch (err) {
  851. const failedAccount = buildHotmailMailApiFailureAccount(workingAccount, err.message);
  852. await upsertHotmailAccount(failedAccount);
  853. throw err;
  854. }
  855. const savedAccount = await upsertHotmailAccount(workingAccount);
  856. return {
  857. account: savedAccount,
  858. mailboxResults,
  859. messages: mailboxResults.flatMap((item) => item.messages),
  860. };
  861. }
  862. async function requestHotmailLocalMessages(account, mailboxes = HOTMAIL_MAILBOXES) {
  863. if (!account?.email) {
  864. throw new Error('Hotmail 账号缺少邮箱地址。');
  865. }
  866. if (!account?.clientId) {
  867. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少客户端 ID。`);
  868. }
  869. if (!account?.refreshToken) {
  870. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少刷新令牌(refresh token)。`);
  871. }
  872. const serviceSettings = getHotmailServiceSettings(await getState());
  873. const { timeoutMs } = getHotmailMailApiRequestConfig();
  874. const requestTimeoutMs = Math.max(timeoutMs, HOTMAIL_LOCAL_HELPER_TIMEOUT_MS);
  875. const controller = new AbortController();
  876. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), requestTimeoutMs);
  877. let response;
  878. try {
  879. response = await fetch(buildHotmailLocalEndpoint(serviceSettings.localBaseUrl, '/messages'), {
  880. method: 'POST',
  881. headers: {
  882. 'Content-Type': 'application/json',
  883. Accept: 'application/json',
  884. },
  885. body: JSON.stringify({
  886. email: account.email,
  887. clientId: account.clientId,
  888. refreshToken: account.refreshToken,
  889. mailboxes,
  890. top: 5,
  891. }),
  892. signal: controller.signal,
  893. });
  894. } catch (err) {
  895. if (err?.name === 'AbortError') {
  896. throw new Error(`Hotmail 本地助手请求超时(>${Math.round(requestTimeoutMs / 1000)} 秒)`);
  897. }
  898. throw new Error(`Hotmail 本地助手请求失败:${err.message}`);
  899. } finally {
  900. clearTimeout(timeoutId);
  901. }
  902. const text = await response.text();
  903. let payload = {};
  904. try {
  905. payload = text ? JSON.parse(text) : {};
  906. } catch {
  907. payload = { raw: text };
  908. }
  909. if (!response.ok || payload?.ok === false) {
  910. const errorText = payload?.error || payload?.message || text || `HTTP ${response.status}`;
  911. throw new Error(`Hotmail 本地助手返回失败:${errorText}`);
  912. }
  913. const rawMessages = Array.isArray(payload?.messages) ? payload.messages : [];
  914. const normalizedMessages = normalizeHotmailMailApiMessages(rawMessages).map((message, index) => ({
  915. ...message,
  916. mailbox: rawMessages[index]?.mailbox || 'INBOX',
  917. receivedTimestamp: Number(rawMessages[index]?.receivedTimestamp || 0) || 0,
  918. }));
  919. const mailboxResults = Array.isArray(payload?.mailboxResults)
  920. ? payload.mailboxResults.map((item) => ({
  921. mailbox: String(item?.mailbox || 'INBOX'),
  922. count: Number(item?.count || 0),
  923. messages: normalizedMessages.filter((message) => String(message.mailbox || 'INBOX') === String(item?.mailbox || 'INBOX')),
  924. }))
  925. : mailboxes.map((mailbox) => ({
  926. mailbox,
  927. count: normalizedMessages.filter((message) => String(message.mailbox || 'INBOX') === mailbox).length,
  928. messages: normalizedMessages.filter((message) => String(message.mailbox || 'INBOX') === mailbox),
  929. }));
  930. const nextAccount = applyHotmailApiResultToAccount(account, {
  931. nextRefreshToken: String(payload?.nextRefreshToken || '').trim(),
  932. });
  933. const savedAccount = await upsertHotmailAccount(nextAccount);
  934. return {
  935. account: savedAccount,
  936. mailboxResults,
  937. messages: normalizedMessages,
  938. };
  939. }
  940. async function requestHotmailLocalCode(account, pollPayload = {}) {
  941. if (!account?.email) {
  942. throw new Error('Hotmail 账号缺少邮箱地址。');
  943. }
  944. if (!account?.clientId) {
  945. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少客户端 ID。`);
  946. }
  947. if (!account?.refreshToken) {
  948. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少刷新令牌(refresh token)。`);
  949. }
  950. const serviceSettings = getHotmailServiceSettings(await getState());
  951. const { timeoutMs } = getHotmailMailApiRequestConfig();
  952. const requestTimeoutMs = Math.max(timeoutMs, HOTMAIL_LOCAL_HELPER_TIMEOUT_MS);
  953. const controller = new AbortController();
  954. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), requestTimeoutMs);
  955. let response;
  956. try {
  957. response = await fetch(buildHotmailLocalEndpoint(serviceSettings.localBaseUrl, '/code'), {
  958. method: 'POST',
  959. headers: {
  960. 'Content-Type': 'application/json',
  961. Accept: 'application/json',
  962. },
  963. body: JSON.stringify({
  964. email: account.email,
  965. clientId: account.clientId,
  966. refreshToken: account.refreshToken,
  967. mailboxes: HOTMAIL_MAILBOXES,
  968. top: 5,
  969. senderFilters: pollPayload.senderFilters || [],
  970. subjectFilters: pollPayload.subjectFilters || [],
  971. excludeCodes: pollPayload.excludeCodes || [],
  972. filterAfterTimestamp: Number(pollPayload.filterAfterTimestamp || 0) || 0,
  973. }),
  974. signal: controller.signal,
  975. });
  976. } catch (err) {
  977. if (err?.name === 'AbortError') {
  978. throw new Error(`Hotmail 本地助手请求超时(>${Math.round(requestTimeoutMs / 1000)} 秒)`);
  979. }
  980. throw new Error(`Hotmail 本地助手请求失败:${err.message}`);
  981. } finally {
  982. clearTimeout(timeoutId);
  983. }
  984. const text = await response.text();
  985. let payload = {};
  986. try {
  987. payload = text ? JSON.parse(text) : {};
  988. } catch {
  989. payload = { raw: text };
  990. }
  991. if (!response.ok || payload?.ok === false) {
  992. const errorText = payload?.error || payload?.message || text || `HTTP ${response.status}`;
  993. throw new Error(`Hotmail 本地助手返回失败:${errorText}`);
  994. }
  995. const normalizedMessage = payload?.message
  996. ? {
  997. ...normalizeHotmailMailApiMessages([payload.message])[0],
  998. mailbox: payload?.message?.mailbox || 'INBOX',
  999. receivedTimestamp: Number(payload?.message?.receivedTimestamp || 0) || 0,
  1000. }
  1001. : null;
  1002. const nextAccount = applyHotmailApiResultToAccount(account, {
  1003. nextRefreshToken: String(payload?.nextRefreshToken || '').trim(),
  1004. });
  1005. const savedAccount = await upsertHotmailAccount(nextAccount);
  1006. return {
  1007. account: savedAccount,
  1008. code: String(payload?.code || ''),
  1009. message: normalizedMessage,
  1010. usedTimeFallback: Boolean(payload?.usedTimeFallback),
  1011. selectionSource: String(payload?.selectionSource || ''),
  1012. };
  1013. }
  1014. async function pollHotmailVerificationCodeViaLocalHelper(step, account, pollPayload = {}) {
  1015. const maxAttempts = Number(pollPayload.maxAttempts) || 5;
  1016. const intervalMs = Number(pollPayload.intervalMs) || 3000;
  1017. let workingAccount = account;
  1018. let lastError = null;
  1019. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  1020. throwIfStopped();
  1021. try {
  1022. await addLog(`步骤 ${step}:正在通过本地助手轮询 Hotmail 验证码(${attempt}/${maxAttempts})...`, 'info');
  1023. const fetchResult = await requestHotmailLocalCode(workingAccount, pollPayload);
  1024. workingAccount = fetchResult.account;
  1025. if (fetchResult.code) {
  1026. const mailboxLabel = fetchResult.message?.mailbox || 'INBOX';
  1027. if (fetchResult.usedTimeFallback) {
  1028. await addLog(`步骤 ${step}:本地助手使用时间回退后命中 Hotmail ${mailboxLabel} 验证码。`, 'warn');
  1029. }
  1030. await addLog(`步骤 ${step}:已通过本地助手在 Hotmail ${mailboxLabel} 中找到验证码:${fetchResult.code}`, 'ok');
  1031. return {
  1032. ok: true,
  1033. code: fetchResult.code,
  1034. emailTimestamp: fetchResult.message?.receivedTimestamp || Date.now(),
  1035. mailId: fetchResult.message?.id || '',
  1036. };
  1037. }
  1038. lastError = new Error(`步骤 ${step}:本地助手暂未返回匹配验证码(${attempt}/${maxAttempts})。`);
  1039. await addLog(lastError.message, attempt === maxAttempts ? 'warn' : 'info');
  1040. } catch (err) {
  1041. lastError = err;
  1042. await addLog(`步骤 ${step}:本地助手轮询 Hotmail 失败:${err.message}`, 'warn');
  1043. }
  1044. if (attempt < maxAttempts) {
  1045. await sleepWithStop(intervalMs);
  1046. }
  1047. }
  1048. throw lastError || new Error(`步骤 ${step}:本地助手未返回新的匹配验证码。`);
  1049. }
  1050. async function fetchHotmailMailboxMessages(account, mailboxes = HOTMAIL_MAILBOXES) {
  1051. const serviceSettings = getHotmailServiceSettings(await getState());
  1052. if (serviceSettings.mode === HOTMAIL_SERVICE_MODE_LOCAL) {
  1053. return requestHotmailLocalMessages(account, mailboxes);
  1054. }
  1055. return fetchHotmailMailboxMessagesFromRemoteService(account, mailboxes);
  1056. }
  1057. async function verifyHotmailAccount(accountId) {
  1058. const state = await getState();
  1059. const account = findHotmailAccount(state.hotmailAccounts, accountId);
  1060. if (!account) {
  1061. throw new Error('未找到需要校验的 Hotmail 账号。');
  1062. }
  1063. const result = await fetchHotmailMailboxMessages(account, ['INBOX']);
  1064. return {
  1065. account: result.account,
  1066. messageCount: result.mailboxResults[0]?.count || 0,
  1067. };
  1068. }
  1069. async function testHotmailAccountMailAccess(accountId) {
  1070. const state = await getState();
  1071. const account = findHotmailAccount(state.hotmailAccounts, accountId);
  1072. if (!account) {
  1073. throw new Error('未找到需要测试的 Hotmail 账号。');
  1074. }
  1075. const result = await fetchHotmailMailboxMessages(account, HOTMAIL_MAILBOXES);
  1076. const latestMessage = getLatestHotmailMessage(result.messages);
  1077. const latestCode = latestMessage ? extractVerificationCodeFromMessage(latestMessage) : null;
  1078. return {
  1079. account: result.account,
  1080. accountId: result.account.id,
  1081. email: result.account.email,
  1082. messageCount: result.messages.length,
  1083. latestSubject: latestMessage?.subject || '',
  1084. latestMailbox: latestMessage?.mailbox || '',
  1085. latestCode: latestCode || '',
  1086. inboxCount: result.mailboxResults.find((item) => item.mailbox === 'INBOX')?.count || 0,
  1087. junkCount: result.mailboxResults.find((item) => item.mailbox === 'Junk')?.count || 0,
  1088. };
  1089. }
  1090. async function pollHotmailVerificationCode(step, state, pollPayload = {}) {
  1091. await addLog(`步骤 ${step}:正在确定 Hotmail 收信账号...`, 'info');
  1092. let account = await ensureHotmailAccountForFlow({
  1093. allowAllocate: true,
  1094. markUsed: false,
  1095. preferredAccountId: state.currentHotmailAccountId || null,
  1096. });
  1097. await addLog(`步骤 ${step}:当前使用 Hotmail 账号 ${account.email} 轮询收件箱。`, 'info');
  1098. const serviceSettings = getHotmailServiceSettings(state);
  1099. if (serviceSettings.mode === HOTMAIL_SERVICE_MODE_LOCAL) {
  1100. return pollHotmailVerificationCodeViaLocalHelper(step, account, pollPayload);
  1101. }
  1102. const maxAttempts = Number(pollPayload.maxAttempts) || 5;
  1103. const intervalMs = Number(pollPayload.intervalMs) || 3000;
  1104. let lastError = null;
  1105. function summarizeMessagesForLog(messages) {
  1106. return (messages || [])
  1107. .slice()
  1108. .sort((left, right) => {
  1109. const leftTime = Date.parse(left.receivedDateTime || '') || 0;
  1110. const rightTime = Date.parse(right.receivedDateTime || '') || 0;
  1111. return rightTime - leftTime;
  1112. })
  1113. .slice(0, 3)
  1114. .map((message) => {
  1115. const receivedAt = message?.receivedDateTime || '未知时间';
  1116. const sender = message?.from?.emailAddress?.address || '未知发件人';
  1117. const subject = message?.subject || '(无主题)';
  1118. const preview = String(message?.bodyPreview || '').replace(/\s+/g, ' ').trim().slice(0, 80);
  1119. return `[${message.mailbox || 'INBOX'}] ${receivedAt} | ${sender} | ${subject} | ${preview}`;
  1120. })
  1121. .join(' || ');
  1122. }
  1123. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  1124. throwIfStopped();
  1125. try {
  1126. await addLog(`步骤 ${step}:正在轮询 Hotmail 邮件(${attempt}/${maxAttempts})...`, 'info');
  1127. const fetchResult = await fetchHotmailMailboxMessages(account, HOTMAIL_MAILBOXES);
  1128. account = fetchResult.account;
  1129. const matchResult = pickVerificationMessageWithTimeFallback(fetchResult.messages, {
  1130. afterTimestamp: pollPayload.filterAfterTimestamp || 0,
  1131. senderFilters: pollPayload.senderFilters || [],
  1132. subjectFilters: pollPayload.subjectFilters || [],
  1133. excludeCodes: pollPayload.excludeCodes || [],
  1134. });
  1135. const match = matchResult.match;
  1136. if (match?.code) {
  1137. const mailboxLabel = match.message?.mailbox || 'INBOX';
  1138. if (matchResult.usedRelaxedFilters) {
  1139. const fallbackLabel = matchResult.usedTimeFallback ? '宽松匹配 + 时间回退' : '宽松匹配';
  1140. await addLog(`步骤 ${step}:严格规则未命中,已改用 ${fallbackLabel} 并命中 Hotmail ${mailboxLabel} 验证码。`, 'warn');
  1141. }
  1142. await addLog(`步骤 ${step}:已在 Hotmail ${mailboxLabel} 中找到验证码:${match.code}`, 'ok');
  1143. return {
  1144. ok: true,
  1145. code: match.code,
  1146. emailTimestamp: match.receivedAt || Date.now(),
  1147. mailId: match.message?.id || '',
  1148. };
  1149. }
  1150. lastError = new Error(`步骤 ${step}:暂未在 Hotmail 收件箱中找到匹配验证码(${attempt}/${maxAttempts})。`);
  1151. await addLog(lastError.message, attempt === maxAttempts ? 'warn' : 'info');
  1152. const mailSummary = summarizeMessagesForLog(fetchResult.messages);
  1153. if (mailSummary) {
  1154. await addLog(`步骤 ${step}:最近邮件样本:${mailSummary}`, 'info');
  1155. }
  1156. } catch (err) {
  1157. lastError = err;
  1158. await addLog(`步骤 ${step}:Hotmail 收件箱轮询失败:${err.message}`, 'warn');
  1159. }
  1160. if (attempt < maxAttempts) {
  1161. await sleepWithStop(intervalMs);
  1162. }
  1163. }
  1164. throw lastError || new Error(`步骤 ${step}:未在 Hotmail 收件箱中找到新的匹配验证码。`);
  1165. }
  1166. function generateRandomSuffix(length = 6) {
  1167. const chars = 'abcdefghjkmnpqrstuvwxyz23456789';
  1168. let suffix = '';
  1169. for (let i = 0; i < length; i++) {
  1170. suffix += chars[Math.floor(Math.random() * chars.length)];
  1171. }
  1172. return suffix;
  1173. }
  1174. function isGeneratedAliasProvider(provider) {
  1175. return provider === '2925';
  1176. }
  1177. function shouldUseCustomRegistrationEmail(state = {}) {
  1178. return isCustomMailProvider(state)
  1179. || (!isHotmailProvider(state)
  1180. && !isGeneratedAliasProvider(state.mailProvider)
  1181. && normalizeEmailGenerator(state.emailGenerator) === 'custom');
  1182. }
  1183. function buildGeneratedAliasEmail(state) {
  1184. const provider = state.mailProvider || '163';
  1185. const emailPrefix = (state.emailPrefix || '').trim();
  1186. if (!emailPrefix) {
  1187. throw new Error('2925 邮箱前缀未设置,请先在侧边栏填写。');
  1188. }
  1189. if (provider === '2925') {
  1190. return `${emailPrefix}${generateRandomSuffix(6)}@2925.com`;
  1191. }
  1192. throw new Error(`未支持的别名邮箱类型:${provider}`);
  1193. }
  1194. function summarizeCloudflareTempEmailMessagesForLog(messages) {
  1195. return (messages || [])
  1196. .slice()
  1197. .sort((left, right) => {
  1198. const leftTime = Date.parse(left.receivedDateTime || '') || 0;
  1199. const rightTime = Date.parse(right.receivedDateTime || '') || 0;
  1200. return rightTime - leftTime;
  1201. })
  1202. .slice(0, 3)
  1203. .map((message) => {
  1204. const receivedAt = message?.receivedDateTime || '未知时间';
  1205. const sender = message?.from?.emailAddress?.address || '未知发件人';
  1206. const subject = message?.subject || '(无主题)';
  1207. const preview = String(message?.bodyPreview || '').replace(/\s+/g, ' ').trim().slice(0, 80);
  1208. const address = message?.address || '未知地址';
  1209. return `[${address}] ${receivedAt} | ${sender} | ${subject} | ${preview}`;
  1210. })
  1211. .join(' || ');
  1212. }
  1213. async function deleteCloudflareTempEmailMail(config, mailId) {
  1214. const normalizedMailId = String(mailId || '').trim();
  1215. if (!normalizedMailId) return false;
  1216. await requestCloudflareTempEmailJson(config, `/admin/mails/${encodeURIComponent(normalizedMailId)}`, {
  1217. method: 'DELETE',
  1218. });
  1219. return true;
  1220. }
  1221. async function listCloudflareTempEmailMessages(state, options = {}) {
  1222. const config = ensureCloudflareTempEmailConfig(state, { requireAdminAuth: true });
  1223. const address = normalizeCloudflareTempEmailAddress(options.address);
  1224. const payload = await requestCloudflareTempEmailJson(config, '/admin/mails', {
  1225. method: 'GET',
  1226. searchParams: {
  1227. limit: Number(options.limit) || CLOUDFLARE_TEMP_EMAIL_DEFAULT_PAGE_SIZE,
  1228. offset: Number(options.offset) || 0,
  1229. address,
  1230. },
  1231. });
  1232. const messages = normalizeCloudflareTempEmailMailApiMessages(payload).filter((message) => {
  1233. if (!address) return true;
  1234. return !message.address || normalizeCloudflareTempEmailAddress(message.address) === address;
  1235. });
  1236. return { config, messages };
  1237. }
  1238. async function pollCloudflareTempEmailVerificationCode(step, state, pollPayload = {}) {
  1239. const targetEmail = normalizeCloudflareTempEmailAddress(pollPayload.targetEmail || state.email);
  1240. if (!targetEmail) {
  1241. throw new Error('Cloudflare Temp Email 轮询前缺少目标邮箱地址。');
  1242. }
  1243. await addLog(`步骤 ${step}:正在轮询 Cloudflare Temp Email 邮件(${targetEmail})...`, 'info');
  1244. const maxAttempts = Number(pollPayload.maxAttempts) || 5;
  1245. const intervalMs = Number(pollPayload.intervalMs) || 3000;
  1246. let lastError = null;
  1247. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  1248. throwIfStopped();
  1249. try {
  1250. const { config, messages } = await listCloudflareTempEmailMessages(state, {
  1251. address: targetEmail,
  1252. limit: pollPayload.limit || CLOUDFLARE_TEMP_EMAIL_DEFAULT_PAGE_SIZE,
  1253. offset: pollPayload.offset || 0,
  1254. });
  1255. const matchResult = pickVerificationMessageWithTimeFallback(messages, {
  1256. afterTimestamp: pollPayload.filterAfterTimestamp || 0,
  1257. senderFilters: pollPayload.senderFilters || [],
  1258. subjectFilters: pollPayload.subjectFilters || [],
  1259. excludeCodes: pollPayload.excludeCodes || [],
  1260. });
  1261. const match = matchResult.match;
  1262. if (match?.code) {
  1263. if (matchResult.usedRelaxedFilters) {
  1264. const fallbackLabel = matchResult.usedTimeFallback ? '宽松匹配 + 时间回退' : '宽松匹配';
  1265. await addLog(`步骤 ${step}:严格规则未命中,已改用 ${fallbackLabel} 并命中 Cloudflare Temp Email 验证码。`, 'warn');
  1266. }
  1267. try {
  1268. await deleteCloudflareTempEmailMail(config, match.message?.id);
  1269. } catch (err) {
  1270. await addLog(`步骤 ${step}:删除 Cloudflare Temp Email 邮件失败:${err.message}`, 'warn');
  1271. }
  1272. return {
  1273. ok: true,
  1274. code: match.code,
  1275. emailTimestamp: match.receivedAt || Date.now(),
  1276. mailId: match.message?.id || '',
  1277. };
  1278. }
  1279. lastError = new Error(`步骤 ${step}:暂未在 Cloudflare Temp Email 中找到匹配验证码(${attempt}/${maxAttempts})。`);
  1280. await addLog(lastError.message, attempt === maxAttempts ? 'warn' : 'info');
  1281. const sample = summarizeCloudflareTempEmailMessagesForLog(messages);
  1282. if (sample) {
  1283. await addLog(`步骤 ${step}:最近邮件样本:${sample}`, 'info');
  1284. }
  1285. } catch (err) {
  1286. lastError = err;
  1287. await addLog(`步骤 ${step}:Cloudflare Temp Email 轮询失败:${err.message}`, 'warn');
  1288. }
  1289. if (attempt < maxAttempts) {
  1290. await sleepWithStop(intervalMs);
  1291. }
  1292. }
  1293. throw lastError || new Error(`步骤 ${step}:未在 Cloudflare Temp Email 中找到新的匹配验证码。`);
  1294. }
  1295. // ============================================================
  1296. // Tab Registry
  1297. // ============================================================
  1298. async function getTabRegistry() {
  1299. const state = await getState();
  1300. return state.tabRegistry || {};
  1301. }
  1302. async function registerTab(source, tabId) {
  1303. const registry = await getTabRegistry();
  1304. registry[source] = { tabId, ready: true };
  1305. await setState({ tabRegistry: registry });
  1306. console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
  1307. }
  1308. async function isTabAlive(source) {
  1309. const registry = await getTabRegistry();
  1310. const entry = registry[source];
  1311. if (!entry) return false;
  1312. try {
  1313. await chrome.tabs.get(entry.tabId);
  1314. return true;
  1315. } catch {
  1316. // Tab no longer exists — clean up registry
  1317. registry[source] = null;
  1318. await setState({ tabRegistry: registry });
  1319. return false;
  1320. }
  1321. }
  1322. async function getTabId(source) {
  1323. const registry = await getTabRegistry();
  1324. return registry[source]?.tabId || null;
  1325. }
  1326. function parseUrlSafely(rawUrl) {
  1327. if (!rawUrl) return null;
  1328. try {
  1329. return new URL(rawUrl);
  1330. } catch {
  1331. return null;
  1332. }
  1333. }
  1334. function normalizeSub2ApiUrl(rawUrl) {
  1335. const input = (rawUrl || '').trim() || DEFAULT_SUB2API_URL;
  1336. const withProtocol = /^https?:\/\//i.test(input) ? input : `https://${input}`;
  1337. const parsed = new URL(withProtocol);
  1338. if (!parsed.pathname || parsed.pathname === '/') {
  1339. parsed.pathname = '/admin/accounts';
  1340. }
  1341. parsed.hash = '';
  1342. return parsed.toString();
  1343. }
  1344. function getPanelMode(state = {}) {
  1345. return state.panelMode === 'sub2api' ? 'sub2api' : 'cpa';
  1346. }
  1347. function getPanelModeLabel(modeOrState) {
  1348. const mode = typeof modeOrState === 'string' ? modeOrState : getPanelMode(modeOrState);
  1349. return mode === 'sub2api' ? 'SUB2API' : 'CPA';
  1350. }
  1351. function isSignupPageHost(hostname = '') {
  1352. return ['auth0.openai.com', 'auth.openai.com', 'accounts.openai.com'].includes(hostname);
  1353. }
  1354. function is163MailHost(hostname = '') {
  1355. return hostname === 'mail.163.com'
  1356. || hostname.endsWith('.mail.163.com')
  1357. || hostname === 'webmail.vip.163.com';
  1358. }
  1359. function isLocalhostOAuthCallbackUrl(rawUrl) {
  1360. const parsed = parseUrlSafely(rawUrl);
  1361. if (!parsed) return false;
  1362. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  1363. if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
  1364. if (!['/auth/callback', '/codex/callback'].includes(parsed.pathname)) return false;
  1365. const code = (parsed.searchParams.get('code') || '').trim();
  1366. const state = (parsed.searchParams.get('state') || '').trim();
  1367. return Boolean(code && state);
  1368. }
  1369. function isLocalCpaUrl(rawUrl) {
  1370. const parsed = parseUrlSafely(rawUrl);
  1371. if (!parsed) return false;
  1372. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  1373. return ['localhost', '127.0.0.1'].includes(parsed.hostname);
  1374. }
  1375. function shouldBypassStep9ForLocalCpa(state) {
  1376. return normalizeLocalCpaStep9Mode(state?.localCpaStep9Mode) === 'bypass'
  1377. && Boolean(state?.localhostUrl)
  1378. && isLocalCpaUrl(state?.vpsUrl);
  1379. }
  1380. function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
  1381. const candidate = parseUrlSafely(candidateUrl);
  1382. if (!candidate) return false;
  1383. const reference = parseUrlSafely(referenceUrl);
  1384. switch (source) {
  1385. case 'signup-page':
  1386. return isSignupPageHost(candidate.hostname);
  1387. case 'duck-mail':
  1388. return candidate.hostname === 'duckduckgo.com' && candidate.pathname.startsWith('/email/');
  1389. case 'qq-mail':
  1390. return candidate.hostname === 'mail.qq.com' || candidate.hostname === 'wx.mail.qq.com';
  1391. case 'mail-163':
  1392. return is163MailHost(candidate.hostname);
  1393. case 'inbucket-mail':
  1394. return Boolean(reference)
  1395. && candidate.origin === reference.origin
  1396. && candidate.pathname.startsWith('/m/');
  1397. case 'mail-2925':
  1398. return candidate.hostname === '2925.com' || candidate.hostname === 'www.2925.com';
  1399. case 'vps-panel':
  1400. return Boolean(reference)
  1401. && candidate.origin === reference.origin
  1402. && candidate.pathname === reference.pathname;
  1403. case 'sub2api-panel':
  1404. return Boolean(reference)
  1405. && candidate.origin === reference.origin
  1406. && (
  1407. candidate.pathname.startsWith('/admin/accounts')
  1408. || candidate.pathname.startsWith('/login')
  1409. || candidate.pathname === '/'
  1410. );
  1411. default:
  1412. return false;
  1413. }
  1414. }
  1415. async function rememberSourceLastUrl(source, url) {
  1416. if (!source || !url) return;
  1417. const state = await getState();
  1418. const sourceLastUrls = { ...(state.sourceLastUrls || {}) };
  1419. sourceLastUrls[source] = url;
  1420. await setState({ sourceLastUrls });
  1421. }
  1422. async function closeConflictingTabsForSource(source, currentUrl, options = {}) {
  1423. const { excludeTabIds = [] } = options;
  1424. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  1425. const state = await getState();
  1426. const lastUrl = state.sourceLastUrls?.[source];
  1427. const referenceUrls = [currentUrl, lastUrl].filter(Boolean);
  1428. if (!referenceUrls.length) return;
  1429. const tabs = await chrome.tabs.query({});
  1430. const matchedIds = tabs
  1431. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  1432. .filter((tab) => referenceUrls.some((refUrl) => matchesSourceUrlFamily(source, tab.url, refUrl)))
  1433. .map(tab => tab.id);
  1434. if (!matchedIds.length) return;
  1435. await chrome.tabs.remove(matchedIds).catch(() => { });
  1436. const registry = await getTabRegistry();
  1437. if (registry[source]?.tabId && matchedIds.includes(registry[source].tabId)) {
  1438. registry[source] = null;
  1439. await setState({ tabRegistry: registry });
  1440. }
  1441. await addLog(`已关闭 ${matchedIds.length} 个旧的${getSourceLabel(source)}标签页。`, 'info');
  1442. }
  1443. function isLocalhostOAuthCallbackTabMatch(callbackUrl, candidateUrl) {
  1444. if (!isLocalhostOAuthCallbackUrl(callbackUrl) || !isLocalhostOAuthCallbackUrl(candidateUrl)) {
  1445. return false;
  1446. }
  1447. const callback = parseUrlSafely(callbackUrl);
  1448. const candidate = parseUrlSafely(candidateUrl);
  1449. if (!callback || !candidate) return false;
  1450. return callback.origin === candidate.origin
  1451. && callback.pathname === candidate.pathname
  1452. && callback.searchParams.get('code') === candidate.searchParams.get('code')
  1453. && callback.searchParams.get('state') === candidate.searchParams.get('state');
  1454. }
  1455. async function closeLocalhostCallbackTabs(callbackUrl, options = {}) {
  1456. if (!isLocalhostOAuthCallbackUrl(callbackUrl)) return 0;
  1457. const { excludeTabIds = [] } = options;
  1458. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  1459. const tabs = await chrome.tabs.query({});
  1460. const matchedIds = tabs
  1461. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  1462. .filter((tab) => isLocalhostOAuthCallbackTabMatch(callbackUrl, tab.url))
  1463. .map((tab) => tab.id);
  1464. if (!matchedIds.length) return 0;
  1465. await chrome.tabs.remove(matchedIds).catch(() => { });
  1466. const registry = await getTabRegistry();
  1467. if (registry['signup-page']?.tabId && matchedIds.includes(registry['signup-page'].tabId)) {
  1468. registry['signup-page'] = null;
  1469. await setState({ tabRegistry: registry });
  1470. }
  1471. await addLog(`已关闭 ${matchedIds.length} 个匹配当前 OAuth callback 的 localhost 残留标签页。`, 'info');
  1472. return matchedIds.length;
  1473. }
  1474. function buildLocalhostCleanupPrefix(rawUrl) {
  1475. if (!isLocalhostOAuthCallbackUrl(rawUrl)) return '';
  1476. const parsed = parseUrlSafely(rawUrl);
  1477. if (!parsed) return '';
  1478. const segments = parsed.pathname.split('/').filter(Boolean);
  1479. if (!segments.length) {
  1480. return parsed.origin;
  1481. }
  1482. return `${parsed.origin}/${segments[0]}`;
  1483. }
  1484. async function closeTabsByUrlPrefix(prefix, options = {}) {
  1485. if (!prefix) return 0;
  1486. const { excludeTabIds = [], excludeUrls = [], excludeLocalhostCallbacks = false } = options;
  1487. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  1488. const excludedUrls = new Set((Array.isArray(excludeUrls) ? excludeUrls : []).filter(Boolean));
  1489. const tabs = await chrome.tabs.query({});
  1490. const matchedIds = tabs
  1491. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  1492. .filter((tab) => typeof tab.url === 'string' && !excludedUrls.has(tab.url))
  1493. .filter((tab) => !(excludeLocalhostCallbacks && isLocalhostOAuthCallbackUrl(tab.url)))
  1494. .filter((tab) => typeof tab.url === 'string' && tab.url.startsWith(prefix))
  1495. .map((tab) => tab.id);
  1496. if (!matchedIds.length) return 0;
  1497. await chrome.tabs.remove(matchedIds).catch(() => { });
  1498. await addLog(`已关闭 ${matchedIds.length} 个匹配 ${prefix} 的 localhost 残留标签页。`, 'info');
  1499. return matchedIds.length;
  1500. }
  1501. async function pingContentScriptOnTab(tabId) {
  1502. if (!Number.isInteger(tabId)) return null;
  1503. try {
  1504. return await chrome.tabs.sendMessage(tabId, {
  1505. type: 'PING',
  1506. source: 'background',
  1507. payload: {},
  1508. });
  1509. } catch {
  1510. return null;
  1511. }
  1512. }
  1513. async function waitForTabUrlFamily(source, tabId, referenceUrl, options = {}) {
  1514. const { timeoutMs = 15000, retryDelayMs = 400 } = options;
  1515. const start = Date.now();
  1516. while (Date.now() - start < timeoutMs) {
  1517. try {
  1518. const tab = await chrome.tabs.get(tabId);
  1519. if (matchesSourceUrlFamily(source, tab.url, referenceUrl)) {
  1520. return tab;
  1521. }
  1522. } catch {
  1523. return null;
  1524. }
  1525. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  1526. }
  1527. return null;
  1528. }
  1529. async function ensureContentScriptReadyOnTab(source, tabId, options = {}) {
  1530. const {
  1531. inject = null,
  1532. injectSource = null,
  1533. timeoutMs = 30000,
  1534. retryDelayMs = 700,
  1535. logMessage = '',
  1536. } = options;
  1537. const start = Date.now();
  1538. let lastError = null;
  1539. let logged = false;
  1540. let attempt = 0;
  1541. console.log(
  1542. LOG_PREFIX,
  1543. `[ensureContentScriptReadyOnTab] start ${source} tab=${tabId}, timeout=${timeoutMs}ms, inject=${Array.isArray(inject) ? inject.join(',') : 'none'}`
  1544. );
  1545. while (Date.now() - start < timeoutMs) {
  1546. attempt += 1;
  1547. const pong = await pingContentScriptOnTab(tabId);
  1548. if (pong?.ok && (!pong.source || pong.source === source)) {
  1549. console.log(
  1550. LOG_PREFIX,
  1551. `[ensureContentScriptReadyOnTab] ready ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  1552. );
  1553. await registerTab(source, tabId);
  1554. return;
  1555. }
  1556. if (!inject || !inject.length) {
  1557. throw new Error(`${getSourceLabel(source)} 内容脚本未就绪,且未提供可用的注入文件。`);
  1558. }
  1559. const registry = await getTabRegistry();
  1560. if (registry[source]) {
  1561. registry[source].ready = false;
  1562. await setState({ tabRegistry: registry });
  1563. }
  1564. try {
  1565. if (injectSource) {
  1566. await chrome.scripting.executeScript({
  1567. target: { tabId },
  1568. func: (injectedSource) => {
  1569. window.__MULTIPAGE_SOURCE = injectedSource;
  1570. },
  1571. args: [injectSource],
  1572. });
  1573. }
  1574. await chrome.scripting.executeScript({
  1575. target: { tabId },
  1576. files: inject,
  1577. });
  1578. } catch (err) {
  1579. lastError = err;
  1580. console.warn(
  1581. LOG_PREFIX,
  1582. `[ensureContentScriptReadyOnTab] inject attempt ${attempt} failed for ${source} tab=${tabId}: ${err?.message || err}`
  1583. );
  1584. }
  1585. const pongAfterInject = await pingContentScriptOnTab(tabId);
  1586. if (pongAfterInject?.ok && (!pongAfterInject.source || pongAfterInject.source === source)) {
  1587. console.log(
  1588. LOG_PREFIX,
  1589. `[ensureContentScriptReadyOnTab] ready after inject ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  1590. );
  1591. await registerTab(source, tabId);
  1592. return;
  1593. }
  1594. if (logMessage && !logged) {
  1595. console.warn(
  1596. LOG_PREFIX,
  1597. `[ensureContentScriptReadyOnTab] ${source} tab=${tabId} still not ready after ${Date.now() - start}ms`
  1598. );
  1599. await addLog(logMessage, 'warn');
  1600. logged = true;
  1601. }
  1602. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  1603. }
  1604. throw lastError || new Error(`${getSourceLabel(source)} 内容脚本长时间未就绪。`);
  1605. }
  1606. // ============================================================
  1607. // Command Queue (for content scripts not yet ready)
  1608. // ============================================================
  1609. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  1610. function getContentScriptResponseTimeoutMs(message) {
  1611. if (!message || typeof message !== 'object') {
  1612. return 30000;
  1613. }
  1614. if (message.type === 'POLL_EMAIL') {
  1615. const maxAttempts = Math.max(1, Number(message.payload?.maxAttempts) || 1);
  1616. const intervalMs = Math.max(0, Number(message.payload?.intervalMs) || 0);
  1617. return Math.max(45000, maxAttempts * intervalMs + 25000);
  1618. }
  1619. if (message.type === 'FILL_CODE') {
  1620. return Number(message.step) === 7 ? 45000 : 30000;
  1621. }
  1622. if (message.type === 'PREPARE_SIGNUP_VERIFICATION') {
  1623. return 45000;
  1624. }
  1625. return 30000;
  1626. }
  1627. function getMessageDebugLabel(source, message, tabId = null) {
  1628. const parts = [source || 'unknown', message?.type || 'UNKNOWN'];
  1629. if (Number.isInteger(message?.step)) {
  1630. parts.push(`step=${message.step}`);
  1631. }
  1632. if (Number.isInteger(tabId)) {
  1633. parts.push(`tab=${tabId}`);
  1634. }
  1635. return parts.join(' ');
  1636. }
  1637. function summarizeMessageResultForDebug(result) {
  1638. if (result === undefined) return 'undefined';
  1639. if (result === null) return 'null';
  1640. if (typeof result !== 'object') return JSON.stringify(result);
  1641. const summary = {};
  1642. for (const key of ['ok', 'error', 'stopped', 'source', 'step']) {
  1643. if (key in result) summary[key] = result[key];
  1644. }
  1645. if (result.payload && typeof result.payload === 'object') {
  1646. summary.payloadKeys = Object.keys(result.payload);
  1647. }
  1648. return JSON.stringify(summary);
  1649. }
  1650. function sendTabMessageWithTimeout(tabId, source, message, responseTimeoutMs = getContentScriptResponseTimeoutMs(message)) {
  1651. return new Promise((resolve, reject) => {
  1652. let settled = false;
  1653. const startedAt = Date.now();
  1654. const debugLabel = getMessageDebugLabel(source, message, tabId);
  1655. console.log(LOG_PREFIX, `[sendTabMessageWithTimeout] dispatch ${debugLabel}, timeout=${responseTimeoutMs}ms`);
  1656. const timer = setTimeout(() => {
  1657. if (settled) return;
  1658. settled = true;
  1659. const seconds = Math.ceil(responseTimeoutMs / 1000);
  1660. console.warn(LOG_PREFIX, `[sendTabMessageWithTimeout] timeout ${debugLabel} after ${Date.now() - startedAt}ms`);
  1661. reject(new Error(`Content script on ${source} did not respond in ${seconds}s. Try refreshing the tab and retry.`));
  1662. }, responseTimeoutMs);
  1663. chrome.tabs.sendMessage(tabId, message)
  1664. .then((value) => {
  1665. const elapsed = Date.now() - startedAt;
  1666. if (settled) {
  1667. console.warn(
  1668. LOG_PREFIX,
  1669. `[sendTabMessageWithTimeout] late response ignored for ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  1670. );
  1671. return;
  1672. }
  1673. settled = true;
  1674. clearTimeout(timer);
  1675. console.log(
  1676. LOG_PREFIX,
  1677. `[sendTabMessageWithTimeout] response ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  1678. );
  1679. resolve(value);
  1680. })
  1681. .catch((error) => {
  1682. const elapsed = Date.now() - startedAt;
  1683. const errorMessage = error?.message || String(error);
  1684. if (settled) {
  1685. console.warn(
  1686. LOG_PREFIX,
  1687. `[sendTabMessageWithTimeout] late rejection ignored for ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  1688. );
  1689. return;
  1690. }
  1691. settled = true;
  1692. clearTimeout(timer);
  1693. console.warn(
  1694. LOG_PREFIX,
  1695. `[sendTabMessageWithTimeout] rejection ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  1696. );
  1697. reject(error);
  1698. });
  1699. });
  1700. }
  1701. function queueCommand(source, message, timeout = 15000) {
  1702. return new Promise((resolve, reject) => {
  1703. const timer = setTimeout(() => {
  1704. pendingCommands.delete(source);
  1705. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  1706. console.error(LOG_PREFIX, err);
  1707. reject(new Error(err));
  1708. }, timeout);
  1709. pendingCommands.set(source, { message, resolve, reject, timer });
  1710. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  1711. });
  1712. }
  1713. function flushCommand(source, tabId) {
  1714. const pending = pendingCommands.get(source);
  1715. if (pending) {
  1716. clearTimeout(pending.timer);
  1717. pendingCommands.delete(source);
  1718. sendTabMessageWithTimeout(tabId, source, pending.message).then(pending.resolve).catch(pending.reject);
  1719. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  1720. }
  1721. }
  1722. function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
  1723. for (const [source, pending] of pendingCommands.entries()) {
  1724. clearTimeout(pending.timer);
  1725. pending.reject(new Error(reason));
  1726. pendingCommands.delete(source);
  1727. console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
  1728. }
  1729. }
  1730. // ============================================================
  1731. // Reuse or create tab
  1732. // ============================================================
  1733. async function reuseOrCreateTab(source, url, options = {}) {
  1734. const alive = await isTabAlive(source);
  1735. if (alive) {
  1736. const tabId = await getTabId(source);
  1737. await closeConflictingTabsForSource(source, url, { excludeTabIds: [tabId] });
  1738. const currentTab = await chrome.tabs.get(tabId);
  1739. const sameUrl = currentTab.url === url;
  1740. const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
  1741. const registry = await getTabRegistry();
  1742. if (sameUrl) {
  1743. await chrome.tabs.update(tabId, { active: true });
  1744. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
  1745. if (shouldReloadOnReuse) {
  1746. if (registry[source]) registry[source].ready = false;
  1747. await setState({ tabRegistry: registry });
  1748. await chrome.tabs.reload(tabId);
  1749. await new Promise((resolve) => {
  1750. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  1751. const listener = (tid, info) => {
  1752. if (tid === tabId && info.status === 'complete') {
  1753. chrome.tabs.onUpdated.removeListener(listener);
  1754. clearTimeout(timer);
  1755. resolve();
  1756. }
  1757. };
  1758. chrome.tabs.onUpdated.addListener(listener);
  1759. });
  1760. }
  1761. // For dynamically injected pages like the VPS panel, re-inject immediately.
  1762. if (options.inject) {
  1763. if (registry[source]) registry[source].ready = false;
  1764. await setState({ tabRegistry: registry });
  1765. if (options.injectSource) {
  1766. await chrome.scripting.executeScript({
  1767. target: { tabId },
  1768. func: (injectedSource) => {
  1769. window.__MULTIPAGE_SOURCE = injectedSource;
  1770. },
  1771. args: [options.injectSource],
  1772. });
  1773. }
  1774. await chrome.scripting.executeScript({
  1775. target: { tabId },
  1776. files: options.inject,
  1777. });
  1778. await new Promise(r => setTimeout(r, 500));
  1779. }
  1780. await rememberSourceLastUrl(source, url);
  1781. return tabId;
  1782. }
  1783. // Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
  1784. if (registry[source]) registry[source].ready = false;
  1785. await setState({ tabRegistry: registry });
  1786. // Navigate existing tab to new URL
  1787. await chrome.tabs.update(tabId, { url, active: true });
  1788. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
  1789. // Wait for page load complete (with 30s timeout)
  1790. await new Promise((resolve) => {
  1791. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  1792. const listener = (tid, info) => {
  1793. if (tid === tabId && info.status === 'complete') {
  1794. chrome.tabs.onUpdated.removeListener(listener);
  1795. clearTimeout(timer);
  1796. resolve();
  1797. }
  1798. };
  1799. chrome.tabs.onUpdated.addListener(listener);
  1800. });
  1801. // If dynamic injection needed (VPS panel), re-inject after navigation
  1802. if (options.inject) {
  1803. if (options.injectSource) {
  1804. await chrome.scripting.executeScript({
  1805. target: { tabId },
  1806. func: (injectedSource) => {
  1807. window.__MULTIPAGE_SOURCE = injectedSource;
  1808. },
  1809. args: [options.injectSource],
  1810. });
  1811. }
  1812. await chrome.scripting.executeScript({
  1813. target: { tabId },
  1814. files: options.inject,
  1815. });
  1816. }
  1817. // Wait a bit for content script to inject and send READY
  1818. await new Promise(r => setTimeout(r, 500));
  1819. await rememberSourceLastUrl(source, url);
  1820. return tabId;
  1821. }
  1822. // Create new tab
  1823. await closeConflictingTabsForSource(source, url);
  1824. const tab = await chrome.tabs.create({ url, active: true });
  1825. console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
  1826. // If dynamic injection needed (VPS panel), inject scripts after load
  1827. if (options.inject) {
  1828. await new Promise((resolve) => {
  1829. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  1830. const listener = (tabId, info) => {
  1831. if (tabId === tab.id && info.status === 'complete') {
  1832. chrome.tabs.onUpdated.removeListener(listener);
  1833. clearTimeout(timer);
  1834. resolve();
  1835. }
  1836. };
  1837. chrome.tabs.onUpdated.addListener(listener);
  1838. });
  1839. if (options.injectSource) {
  1840. await chrome.scripting.executeScript({
  1841. target: { tabId: tab.id },
  1842. func: (injectedSource) => {
  1843. window.__MULTIPAGE_SOURCE = injectedSource;
  1844. },
  1845. args: [options.injectSource],
  1846. });
  1847. }
  1848. await chrome.scripting.executeScript({
  1849. target: { tabId: tab.id },
  1850. files: options.inject,
  1851. });
  1852. }
  1853. await rememberSourceLastUrl(source, url);
  1854. return tab.id;
  1855. }
  1856. // ============================================================
  1857. // Send command to content script (with readiness check)
  1858. // ============================================================
  1859. async function sendToContentScript(source, message, options = {}) {
  1860. throwIfStopped();
  1861. const { responseTimeoutMs = getContentScriptResponseTimeoutMs(message) } = options;
  1862. const registry = await getTabRegistry();
  1863. const entry = registry[source];
  1864. if (!entry || !entry.ready) {
  1865. throwIfStopped();
  1866. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  1867. return queueCommand(source, message);
  1868. }
  1869. // Verify tab is still alive
  1870. const alive = await isTabAlive(source);
  1871. throwIfStopped();
  1872. if (!alive) {
  1873. // Tab was closed — queue the command, it will be sent when tab is reopened
  1874. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  1875. return queueCommand(source, message);
  1876. }
  1877. throwIfStopped();
  1878. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  1879. return sendTabMessageWithTimeout(entry.tabId, source, message, responseTimeoutMs);
  1880. }
  1881. async function sendToContentScriptResilient(source, message, options = {}) {
  1882. const { timeoutMs = 30000, retryDelayMs = 600, logMessage = '' } = options;
  1883. const start = Date.now();
  1884. let lastError = null;
  1885. let logged = false;
  1886. let attempt = 0;
  1887. const debugLabel = getMessageDebugLabel(source, message);
  1888. console.log(
  1889. LOG_PREFIX,
  1890. `[sendToContentScriptResilient] start ${debugLabel}, totalTimeout=${timeoutMs}ms, retryDelay=${retryDelayMs}ms`
  1891. );
  1892. while (Date.now() - start < timeoutMs) {
  1893. throwIfStopped();
  1894. attempt += 1;
  1895. try {
  1896. console.log(
  1897. LOG_PREFIX,
  1898. `[sendToContentScriptResilient] attempt ${attempt} -> ${debugLabel}, elapsed=${Date.now() - start}ms`
  1899. );
  1900. const result = await sendToContentScript(source, message);
  1901. console.log(
  1902. LOG_PREFIX,
  1903. `[sendToContentScriptResilient] success ${debugLabel} on attempt ${attempt} after ${Date.now() - start}ms`
  1904. );
  1905. return result;
  1906. } catch (err) {
  1907. const retryable = isRetryableContentScriptTransportError(err);
  1908. console.warn(
  1909. LOG_PREFIX,
  1910. `[sendToContentScriptResilient] attempt ${attempt} failed for ${debugLabel}, retryable=${retryable}, elapsed=${Date.now() - start}ms: ${err?.message || err}`
  1911. );
  1912. if (!retryable) {
  1913. throw err;
  1914. }
  1915. lastError = err;
  1916. if (logMessage && !logged) {
  1917. await addLog(logMessage, 'warn');
  1918. logged = true;
  1919. }
  1920. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  1921. }
  1922. }
  1923. throw lastError || new Error(`等待 ${getSourceLabel(source)} 重新就绪超时。`);
  1924. }
  1925. async function sendToMailContentScriptResilient(mail, message, options = {}) {
  1926. const { timeoutMs = 45000, maxRecoveryAttempts = 2 } = options;
  1927. const start = Date.now();
  1928. let lastError = null;
  1929. let recoveries = 0;
  1930. let logged = false;
  1931. while (Date.now() - start < timeoutMs) {
  1932. throwIfStopped();
  1933. try {
  1934. return await sendToContentScript(mail.source, message);
  1935. } catch (err) {
  1936. if (!isRetryableContentScriptTransportError(err)) {
  1937. throw err;
  1938. }
  1939. lastError = err;
  1940. if (!logged) {
  1941. await addLog(`步骤 ${message.step}:${mail.label} 页面通信异常,正在尝试让邮箱页重新就绪...`, 'warn');
  1942. logged = true;
  1943. }
  1944. if (recoveries >= maxRecoveryAttempts) {
  1945. break;
  1946. }
  1947. recoveries += 1;
  1948. await reuseOrCreateTab(mail.source, mail.url, {
  1949. inject: mail.inject,
  1950. injectSource: mail.injectSource,
  1951. reloadIfSameUrl: true,
  1952. });
  1953. await new Promise((resolve) => setTimeout(resolve, 800));
  1954. }
  1955. }
  1956. throw lastError || new Error(`${mail.label} 页面未能重新就绪。`);
  1957. }
  1958. // ============================================================
  1959. // Logging
  1960. // ============================================================
  1961. async function addLog(message, level = 'info') {
  1962. const state = await getState();
  1963. const logs = state.logs || [];
  1964. const entry = { message, level, timestamp: Date.now() };
  1965. logs.push(entry);
  1966. // Keep last 500 logs
  1967. if (logs.length > 500) logs.splice(0, logs.length - 500);
  1968. await setState({ logs });
  1969. // Broadcast to side panel
  1970. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => { });
  1971. }
  1972. function getStep8CallbackUrlFromNavigation(details, signupTabId) {
  1973. if (!Number.isInteger(signupTabId) || !details) return '';
  1974. if (details.tabId !== signupTabId) return '';
  1975. if (details.frameId !== 0) return '';
  1976. return isLocalhostOAuthCallbackUrl(details.url) ? details.url : '';
  1977. }
  1978. function getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId) {
  1979. if (!Number.isInteger(signupTabId) || tabId !== signupTabId) return '';
  1980. const candidates = [changeInfo?.url, tab?.url];
  1981. for (const candidate of candidates) {
  1982. if (isLocalhostOAuthCallbackUrl(candidate)) {
  1983. return candidate;
  1984. }
  1985. }
  1986. return '';
  1987. }
  1988. function getSourceLabel(source) {
  1989. const labels = {
  1990. 'sidepanel': '侧边栏',
  1991. 'signup-page': '认证页',
  1992. 'vps-panel': 'CPA 面板',
  1993. 'sub2api-panel': 'SUB2API 后台',
  1994. 'qq-mail': 'QQ 邮箱',
  1995. 'mail-163': '163 邮箱',
  1996. 'mail-2925': '2925 邮箱',
  1997. 'inbucket-mail': 'Inbucket 邮箱',
  1998. 'duck-mail': 'Duck 邮箱',
  1999. 'hotmail-api': 'Hotmail(远程/本地)',
  2000. 'cloudflare-temp-email': 'Cloudflare Temp Email',
  2001. };
  2002. return labels[source] || source || '未知来源';
  2003. }
  2004. // ============================================================
  2005. // Step Status Management
  2006. // ============================================================
  2007. async function setStepStatus(step, status) {
  2008. const state = await getState();
  2009. const statuses = { ...state.stepStatuses };
  2010. statuses[step] = status;
  2011. await setState({ stepStatuses: statuses, currentStep: step });
  2012. // Broadcast to side panel
  2013. chrome.runtime.sendMessage({
  2014. type: 'STEP_STATUS_CHANGED',
  2015. payload: { step, status },
  2016. }).catch(() => { });
  2017. }
  2018. function isStopError(error) {
  2019. const message = typeof error === 'string' ? error : error?.message;
  2020. return message === STOP_ERROR_MESSAGE;
  2021. }
  2022. function isRetryableContentScriptTransportError(error) {
  2023. const message = String(typeof error === 'string' ? error : error?.message || '');
  2024. 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);
  2025. }
  2026. function getErrorMessage(error) {
  2027. return String(typeof error === 'string' ? error : error?.message || '');
  2028. }
  2029. function isVerificationMailPollingError(error) {
  2030. const message = getErrorMessage(error);
  2031. return /未在 .*邮箱中找到新的匹配邮件|未在 Hotmail 收件箱中找到新的匹配验证码|邮箱轮询结束,但未获取到验证码|无法获取新的(?:注册|登录)验证码|页面未能重新就绪|页面通信异常|did not respond in \d+s/i.test(message);
  2032. }
  2033. const STEP7_RESTART_FROM_STEP6_ERROR_CODE = 'STEP7_RESTART_FROM_STEP6';
  2034. const STEP7_RESTART_FROM_STEP6_MARKER_PATTERN = /^STEP7_RESTART_FROM_STEP6::([^:]+)::(.*)$/;
  2035. function createStep7RestartFromStep6Error(details = {}) {
  2036. const { reason = 'unknown', url = '' } = details || {};
  2037. const reasonLabel = reason === 'login_timeout_error_page'
  2038. ? '检测到登录页超时报错'
  2039. : '步骤 7 请求回到步骤 6';
  2040. const error = new Error(`步骤 7:${reasonLabel}。${url ? `URL: ${url}` : ''}`.trim());
  2041. error.code = STEP7_RESTART_FROM_STEP6_ERROR_CODE;
  2042. error.restartReason = reason;
  2043. error.restartUrl = url;
  2044. return error;
  2045. }
  2046. function parseStep7RestartFromStep6Marker(message) {
  2047. const normalized = getErrorMessage(message);
  2048. const match = normalized.match(STEP7_RESTART_FROM_STEP6_MARKER_PATTERN);
  2049. if (!match) {
  2050. return null;
  2051. }
  2052. return {
  2053. reason: match[1] || 'unknown',
  2054. url: match[2] || '',
  2055. };
  2056. }
  2057. function getStep7RestartFromStep6Error(result) {
  2058. if (result?.restartFromStep6) {
  2059. return createStep7RestartFromStep6Error(result);
  2060. }
  2061. const parsed = parseStep7RestartFromStep6Marker(result?.error);
  2062. if (!parsed) {
  2063. return null;
  2064. }
  2065. return createStep7RestartFromStep6Error(parsed);
  2066. }
  2067. function isStep7RestartFromStep6Error(error) {
  2068. return error?.code === STEP7_RESTART_FROM_STEP6_ERROR_CODE
  2069. || Boolean(parseStep7RestartFromStep6Marker(error));
  2070. }
  2071. function isRestartCurrentAttemptError(error) {
  2072. const message = String(typeof error === 'string' ? error : error?.message || '');
  2073. return /当前邮箱已存在,需要重新开始新一轮/.test(message);
  2074. }
  2075. function isStep9RecoverableAuthError(error) {
  2076. const message = String(typeof error === 'string' ? error : error?.message || '');
  2077. return /STEP9_OAUTH_RETRY::/i.test(message)
  2078. || isRecoverableStep9AuthFailure(message);
  2079. }
  2080. function isLegacyStep9RecoverableAuthError(error) {
  2081. const message = String(typeof error === 'string' ? error : error?.message || '');
  2082. return /STEP9_OAUTH_TIMEOUT::|认证失败:\s*Timeout waiting for OAuth callback/i.test(message);
  2083. }
  2084. function isStepDoneStatus(status) {
  2085. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  2086. }
  2087. function getFirstUnfinishedStep(statuses = {}) {
  2088. for (let step = 1; step <= 9; step++) {
  2089. if (!isStepDoneStatus(statuses[step] || 'pending')) {
  2090. return step;
  2091. }
  2092. }
  2093. return null;
  2094. }
  2095. function hasSavedProgress(statuses = {}) {
  2096. return Object.values({ ...DEFAULT_STATE.stepStatuses, ...statuses }).some((status) => status !== 'pending');
  2097. }
  2098. function getDownstreamStateResets(step) {
  2099. if (step <= 1) {
  2100. return {
  2101. oauthUrl: null,
  2102. sub2apiSessionId: null,
  2103. sub2apiOAuthState: null,
  2104. sub2apiGroupId: null,
  2105. sub2apiDraftName: null,
  2106. flowStartTime: null,
  2107. password: null,
  2108. lastEmailTimestamp: null,
  2109. signupVerificationRequestedAt: null,
  2110. loginVerificationRequestedAt: null,
  2111. lastSignupCode: null,
  2112. lastLoginCode: null,
  2113. localhostUrl: null,
  2114. };
  2115. }
  2116. if (step === 2) {
  2117. return {
  2118. password: null,
  2119. lastEmailTimestamp: null,
  2120. signupVerificationRequestedAt: null,
  2121. loginVerificationRequestedAt: null,
  2122. lastSignupCode: null,
  2123. lastLoginCode: null,
  2124. localhostUrl: null,
  2125. };
  2126. }
  2127. if (step === 3 || step === 4) {
  2128. return {
  2129. lastEmailTimestamp: null,
  2130. signupVerificationRequestedAt: null,
  2131. loginVerificationRequestedAt: null,
  2132. lastSignupCode: null,
  2133. lastLoginCode: null,
  2134. localhostUrl: null,
  2135. };
  2136. }
  2137. if (step === 5 || step === 6 || step === 7) {
  2138. return {
  2139. lastLoginCode: null,
  2140. loginVerificationRequestedAt: null,
  2141. localhostUrl: null,
  2142. };
  2143. }
  2144. if (step === 8) {
  2145. return {
  2146. localhostUrl: null,
  2147. };
  2148. }
  2149. return {};
  2150. }
  2151. async function invalidateDownstreamAfterStepRestart(step, options = {}) {
  2152. const { logLabel = `步骤 ${step} 重新执行` } = options;
  2153. const state = await getState();
  2154. const statuses = { ...(state.stepStatuses || {}) };
  2155. const changedSteps = [];
  2156. for (let downstream = step + 1; downstream <= 9; downstream++) {
  2157. if (statuses[downstream] !== 'pending') {
  2158. statuses[downstream] = 'pending';
  2159. changedSteps.push(downstream);
  2160. }
  2161. }
  2162. if (changedSteps.length) {
  2163. await setState({ stepStatuses: statuses });
  2164. for (const downstream of changedSteps) {
  2165. chrome.runtime.sendMessage({
  2166. type: 'STEP_STATUS_CHANGED',
  2167. payload: { step: downstream, status: 'pending' },
  2168. }).catch(() => { });
  2169. }
  2170. await addLog(`${logLabel},已重置后续步骤状态:${changedSteps.join(', ')}`, 'warn');
  2171. }
  2172. const resets = getDownstreamStateResets(step);
  2173. if (Object.keys(resets).length) {
  2174. await setState(resets);
  2175. broadcastDataUpdate(resets);
  2176. }
  2177. }
  2178. function clearStopRequest() {
  2179. stopRequested = false;
  2180. autoRunCountdownSkipRequested = false;
  2181. }
  2182. function getRunningSteps(statuses = {}) {
  2183. return Object.entries({ ...DEFAULT_STATE.stepStatuses, ...statuses })
  2184. .filter(([, status]) => status === 'running')
  2185. .map(([step]) => Number(step))
  2186. .sort((a, b) => a - b);
  2187. }
  2188. function getAutoRunStatusPayload(phase, payload = {}) {
  2189. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  2190. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  2191. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  2192. const rawScheduledAt = phase === 'scheduled'
  2193. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  2194. : null;
  2195. const scheduledAt = rawScheduledAt === null ? null : Number(rawScheduledAt);
  2196. const rawCountdownAt = payload.countdownAt ?? payload.autoRunCountdownAt ?? null;
  2197. const countdownAt = rawCountdownAt === null ? null : Number(rawCountdownAt);
  2198. const countdownTitle = payload.countdownTitle === undefined
  2199. ? ''
  2200. : String(payload.countdownTitle || '');
  2201. const countdownNote = payload.countdownNote === undefined
  2202. ? ''
  2203. : String(payload.countdownNote || '');
  2204. const autoRunning = phase === 'scheduled'
  2205. || phase === 'running'
  2206. || phase === 'waiting_step'
  2207. || phase === 'waiting_email'
  2208. || phase === 'retrying'
  2209. || phase === 'waiting_interval';
  2210. return {
  2211. autoRunning,
  2212. autoRunPhase: phase,
  2213. autoRunCurrentRun: currentRun,
  2214. autoRunTotalRuns: totalRuns,
  2215. autoRunAttemptRun: attemptRun,
  2216. scheduledAutoRunAt: Number.isFinite(scheduledAt) ? scheduledAt : null,
  2217. autoRunCountdownAt: Number.isFinite(countdownAt) ? countdownAt : null,
  2218. autoRunCountdownTitle: countdownTitle,
  2219. autoRunCountdownNote: countdownNote,
  2220. };
  2221. }
  2222. async function broadcastAutoRunStatus(phase, payload = {}, extraState = {}) {
  2223. const rawScheduledAt = phase === 'scheduled'
  2224. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  2225. : null;
  2226. const rawCountdownAt = payload.countdownAt ?? payload.autoRunCountdownAt ?? null;
  2227. const statusPayload = {
  2228. phase,
  2229. currentRun: payload.currentRun ?? autoRunCurrentRun,
  2230. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  2231. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  2232. scheduledAt: rawScheduledAt === null ? null : Number(rawScheduledAt),
  2233. countdownAt: rawCountdownAt === null ? null : Number(rawCountdownAt),
  2234. countdownTitle: payload.countdownTitle === undefined ? '' : String(payload.countdownTitle || ''),
  2235. countdownNote: payload.countdownNote === undefined ? '' : String(payload.countdownNote || ''),
  2236. };
  2237. await setState({
  2238. ...extraState,
  2239. ...getAutoRunStatusPayload(phase, statusPayload),
  2240. });
  2241. chrome.runtime.sendMessage({
  2242. type: 'AUTO_RUN_STATUS',
  2243. payload: statusPayload,
  2244. }).catch(() => { });
  2245. }
  2246. function isAutoRunLockedState(state) {
  2247. return Boolean(state.autoRunning)
  2248. && (
  2249. state.autoRunPhase === 'running'
  2250. || state.autoRunPhase === 'waiting_step'
  2251. || state.autoRunPhase === 'retrying'
  2252. || state.autoRunPhase === 'waiting_interval'
  2253. );
  2254. }
  2255. function isAutoRunPausedState(state) {
  2256. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  2257. }
  2258. function isAutoRunScheduledState(state) {
  2259. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  2260. return Boolean(state.autoRunning)
  2261. && state.autoRunPhase === 'scheduled'
  2262. && Number.isFinite(scheduledAt)
  2263. && Boolean(normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan));
  2264. }
  2265. function formatAutoRunScheduleTime(timestamp) {
  2266. return new Date(timestamp).toLocaleString('zh-CN', {
  2267. hour12: false,
  2268. timeZone: DISPLAY_TIMEZONE,
  2269. month: '2-digit',
  2270. day: '2-digit',
  2271. hour: '2-digit',
  2272. minute: '2-digit',
  2273. second: '2-digit',
  2274. });
  2275. }
  2276. async function setAutoRunDelayEnabledState(enabled) {
  2277. const normalized = Boolean(enabled);
  2278. await setPersistentSettings({ autoRunDelayEnabled: normalized });
  2279. await setState({ autoRunDelayEnabled: normalized });
  2280. broadcastDataUpdate({ autoRunDelayEnabled: normalized });
  2281. }
  2282. async function ensureScheduledAutoRunAlarm(scheduledAt) {
  2283. if (!Number.isFinite(scheduledAt) || scheduledAt <= Date.now()) {
  2284. return false;
  2285. }
  2286. const existingAlarm = await chrome.alarms.get(AUTO_RUN_ALARM_NAME);
  2287. if (!existingAlarm || Math.abs((existingAlarm.scheduledTime || 0) - scheduledAt) > 1000) {
  2288. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  2289. await chrome.alarms.create(AUTO_RUN_ALARM_NAME, { when: scheduledAt });
  2290. }
  2291. return true;
  2292. }
  2293. async function clearScheduledAutoRunAlarm() {
  2294. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  2295. }
  2296. async function scheduleAutoRun(totalRuns, options = {}) {
  2297. const state = await getState();
  2298. if (isAutoRunLockedState(state) || isAutoRunPausedState(state) || autoRunActive) {
  2299. throw new Error('自动运行已在进行中,请先停止后再重新计划。');
  2300. }
  2301. if (isAutoRunScheduledState(state)) {
  2302. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  2303. }
  2304. const delayMinutes = normalizeAutoRunDelayMinutes(options.delayMinutes);
  2305. const plan = normalizeScheduledAutoRunPlan({
  2306. totalRuns,
  2307. autoRunSkipFailures: options.autoRunSkipFailures,
  2308. mode: options.mode,
  2309. });
  2310. const scheduledAt = Date.now() + delayMinutes * 60 * 1000;
  2311. autoRunCurrentRun = 0;
  2312. autoRunTotalRuns = plan.totalRuns;
  2313. autoRunAttemptRun = 0;
  2314. await ensureScheduledAutoRunAlarm(scheduledAt);
  2315. await broadcastAutoRunStatus(
  2316. 'scheduled',
  2317. {
  2318. currentRun: 0,
  2319. totalRuns: plan.totalRuns,
  2320. attemptRun: 0,
  2321. scheduledAt,
  2322. countdownAt: scheduledAt,
  2323. countdownTitle: '已计划自动运行',
  2324. countdownNote: `计划于 ${formatAutoRunScheduleTime(scheduledAt)} 开始`,
  2325. },
  2326. {
  2327. autoRunSkipFailures: plan.autoRunSkipFailures,
  2328. scheduledAutoRunPlan: plan,
  2329. }
  2330. );
  2331. await addLog(
  2332. `自动运行已计划:${delayMinutes} 分钟后启动(${formatAutoRunScheduleTime(scheduledAt)}),目标 ${plan.totalRuns} 轮。`,
  2333. 'info'
  2334. );
  2335. return { ok: true, scheduledAt };
  2336. }
  2337. let scheduledAutoRunLaunching = false;
  2338. async function launchScheduledAutoRun(trigger = 'alarm') {
  2339. if (scheduledAutoRunLaunching) {
  2340. return false;
  2341. }
  2342. scheduledAutoRunLaunching = true;
  2343. try {
  2344. const state = await getState();
  2345. if (!isAutoRunScheduledState(state)) {
  2346. return false;
  2347. }
  2348. if (autoRunActive) {
  2349. return false;
  2350. }
  2351. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  2352. if (!plan) {
  2353. await clearScheduledAutoRunAlarm();
  2354. await broadcastAutoRunStatus('idle', {
  2355. currentRun: 0,
  2356. totalRuns: 1,
  2357. attemptRun: 0,
  2358. }, {
  2359. scheduledAutoRunPlan: null,
  2360. });
  2361. return false;
  2362. }
  2363. await clearScheduledAutoRunAlarm();
  2364. if (trigger !== 'manual' && state.autoRunDelayEnabled) {
  2365. await setAutoRunDelayEnabledState(false);
  2366. }
  2367. await broadcastAutoRunStatus(
  2368. 'running',
  2369. {
  2370. currentRun: 0,
  2371. totalRuns: plan.totalRuns,
  2372. attemptRun: 0,
  2373. },
  2374. {
  2375. autoRunSkipFailures: plan.autoRunSkipFailures,
  2376. scheduledAutoRunPlan: null,
  2377. }
  2378. );
  2379. clearStopRequest();
  2380. await addLog(
  2381. trigger === 'manual'
  2382. ? '已手动跳过倒计时,自动运行立即开始。'
  2383. : '倒计时结束,自动运行开始执行。',
  2384. 'info'
  2385. );
  2386. startAutoRunLoop(plan.totalRuns, {
  2387. autoRunSkipFailures: Boolean(plan.autoRunSkipFailures),
  2388. mode: plan.mode,
  2389. });
  2390. return true;
  2391. } finally {
  2392. scheduledAutoRunLaunching = false;
  2393. }
  2394. }
  2395. async function cancelScheduledAutoRun(options = {}) {
  2396. const state = await getState();
  2397. if (!isAutoRunScheduledState(state)) {
  2398. return false;
  2399. }
  2400. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  2401. await clearScheduledAutoRunAlarm();
  2402. autoRunCurrentRun = 0;
  2403. autoRunTotalRuns = plan?.totalRuns || 1;
  2404. autoRunAttemptRun = 0;
  2405. await broadcastAutoRunStatus(
  2406. 'idle',
  2407. {
  2408. currentRun: 0,
  2409. totalRuns: plan?.totalRuns || 1,
  2410. attemptRun: 0,
  2411. },
  2412. {
  2413. scheduledAutoRunPlan: null,
  2414. }
  2415. );
  2416. if (options.logMessage !== false) {
  2417. await addLog(options.logMessage || '已取消自动运行倒计时计划。', 'warn');
  2418. }
  2419. return true;
  2420. }
  2421. async function restoreScheduledAutoRunIfNeeded() {
  2422. const state = await getState();
  2423. if (state.autoRunPhase !== 'scheduled') {
  2424. return;
  2425. }
  2426. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  2427. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  2428. if (!plan || !Number.isFinite(scheduledAt)) {
  2429. await clearScheduledAutoRunAlarm();
  2430. await broadcastAutoRunStatus('idle', {
  2431. currentRun: 0,
  2432. totalRuns: 1,
  2433. attemptRun: 0,
  2434. }, {
  2435. scheduledAutoRunPlan: null,
  2436. });
  2437. return;
  2438. }
  2439. if (scheduledAt <= Date.now()) {
  2440. await launchScheduledAutoRun('restore');
  2441. return;
  2442. }
  2443. await ensureScheduledAutoRunAlarm(scheduledAt);
  2444. }
  2445. async function ensureManualInteractionAllowed(actionLabel) {
  2446. const state = await getState();
  2447. if (isAutoRunLockedState(state)) {
  2448. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  2449. }
  2450. if (isAutoRunPausedState(state)) {
  2451. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  2452. }
  2453. if (isAutoRunScheduledState(state)) {
  2454. throw new Error(`自动流程已计划启动。请先取消计划,或立即开始后再${actionLabel}。`);
  2455. }
  2456. return state;
  2457. }
  2458. async function skipStep(step) {
  2459. const state = await ensureManualInteractionAllowed('跳过步骤');
  2460. if (!Number.isInteger(step) || step < 1 || step > 9) {
  2461. throw new Error(`无效步骤:${step}`);
  2462. }
  2463. const statuses = { ...(state.stepStatuses || {}) };
  2464. const currentStatus = statuses[step];
  2465. if (currentStatus === 'running') {
  2466. throw new Error(`步骤 ${step} 正在运行中,不能跳过。`);
  2467. }
  2468. if (isStepDoneStatus(currentStatus)) {
  2469. throw new Error(`步骤 ${step} 已完成,无需再跳过。`);
  2470. }
  2471. if (step > 1) {
  2472. const prevStatus = statuses[step - 1];
  2473. if (!isStepDoneStatus(prevStatus)) {
  2474. throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`);
  2475. }
  2476. }
  2477. await setStepStatus(step, 'skipped');
  2478. await addLog(`步骤 ${step} 已跳过`, 'warn');
  2479. if (step === 1) {
  2480. const latestState = await getState();
  2481. const step2Status = latestState.stepStatuses?.[2];
  2482. if (!isStepDoneStatus(step2Status) && step2Status !== 'running') {
  2483. await setStepStatus(2, 'skipped');
  2484. await addLog('步骤 1 已跳过,步骤 2 也已同时跳过。', 'warn');
  2485. }
  2486. }
  2487. return { ok: true, step, status: 'skipped' };
  2488. }
  2489. function throwIfStopped() {
  2490. if (stopRequested) {
  2491. throw new Error(STOP_ERROR_MESSAGE);
  2492. }
  2493. }
  2494. async function sleepWithStop(ms) {
  2495. const start = Date.now();
  2496. while (Date.now() - start < ms) {
  2497. throwIfStopped();
  2498. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  2499. }
  2500. }
  2501. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  2502. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  2503. await sleepWithStop(duration);
  2504. }
  2505. async function clickWithDebugger(tabId, rect) {
  2506. throwIfStopped();
  2507. if (!tabId) {
  2508. throw new Error('未找到用于调试点击的认证页面标签页。');
  2509. }
  2510. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  2511. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  2512. }
  2513. const target = { tabId };
  2514. try {
  2515. await chrome.debugger.attach(target, '1.3');
  2516. } catch (err) {
  2517. throw new Error(
  2518. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  2519. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  2520. );
  2521. }
  2522. try {
  2523. throwIfStopped();
  2524. const x = Math.round(rect.centerX);
  2525. const y = Math.round(rect.centerY);
  2526. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  2527. throwIfStopped();
  2528. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  2529. type: 'mouseMoved',
  2530. x,
  2531. y,
  2532. button: 'none',
  2533. buttons: 0,
  2534. clickCount: 0,
  2535. });
  2536. throwIfStopped();
  2537. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  2538. type: 'mousePressed',
  2539. x,
  2540. y,
  2541. button: 'left',
  2542. buttons: 1,
  2543. clickCount: 1,
  2544. });
  2545. throwIfStopped();
  2546. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  2547. type: 'mouseReleased',
  2548. x,
  2549. y,
  2550. button: 'left',
  2551. buttons: 0,
  2552. clickCount: 1,
  2553. });
  2554. } finally {
  2555. await chrome.debugger.detach(target).catch(() => { });
  2556. }
  2557. }
  2558. async function broadcastStopToContentScripts() {
  2559. const registry = await getTabRegistry();
  2560. for (const entry of Object.values(registry)) {
  2561. if (!entry?.tabId) continue;
  2562. try {
  2563. await chrome.tabs.sendMessage(entry.tabId, {
  2564. type: 'STOP_FLOW',
  2565. source: 'background',
  2566. payload: {},
  2567. });
  2568. } catch { }
  2569. }
  2570. }
  2571. let stopRequested = false;
  2572. let autoRunCountdownSkipRequested = false;
  2573. // ============================================================
  2574. // Message Handler (central router)
  2575. // ============================================================
  2576. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  2577. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  2578. handleMessage(message, sender).then(response => {
  2579. sendResponse(response);
  2580. }).catch(err => {
  2581. console.error(LOG_PREFIX, 'Handler error:', err);
  2582. sendResponse({ error: err.message });
  2583. });
  2584. return true; // async response
  2585. });
  2586. async function handleMessage(message, sender) {
  2587. switch (message.type) {
  2588. case 'CONTENT_SCRIPT_READY': {
  2589. const tabId = sender.tab?.id;
  2590. if (tabId && message.source) {
  2591. await registerTab(message.source, tabId);
  2592. flushCommand(message.source, tabId);
  2593. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  2594. }
  2595. return { ok: true };
  2596. }
  2597. case 'LOG': {
  2598. const { message: msg, level } = message.payload;
  2599. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  2600. return { ok: true };
  2601. }
  2602. case 'STEP_COMPLETE': {
  2603. if (stopRequested) {
  2604. await setStepStatus(message.step, 'stopped');
  2605. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  2606. return { ok: true };
  2607. }
  2608. await setStepStatus(message.step, 'completed');
  2609. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  2610. await handleStepData(message.step, message.payload);
  2611. notifyStepComplete(message.step, message.payload);
  2612. return { ok: true };
  2613. }
  2614. case 'STEP_ERROR': {
  2615. if (isStopError(message.error)) {
  2616. await setStepStatus(message.step, 'stopped');
  2617. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  2618. notifyStepError(message.step, message.error);
  2619. } else {
  2620. await setStepStatus(message.step, 'failed');
  2621. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  2622. notifyStepError(message.step, message.error);
  2623. }
  2624. return { ok: true };
  2625. }
  2626. case 'GET_STATE': {
  2627. return await getState();
  2628. }
  2629. case 'RESET': {
  2630. clearStopRequest();
  2631. await clearScheduledAutoRunAlarm();
  2632. await resetState();
  2633. await addLog('流程已重置', 'info');
  2634. return { ok: true };
  2635. }
  2636. case 'EXECUTE_STEP': {
  2637. clearStopRequest();
  2638. if (message.source === 'sidepanel') {
  2639. await ensureManualInteractionAllowed('手动执行步骤');
  2640. }
  2641. const step = message.payload.step;
  2642. if (message.source === 'sidepanel') {
  2643. await invalidateDownstreamAfterStepRestart(step, { logLabel: `步骤 ${step} 重新执行` });
  2644. }
  2645. // Save email if provided (from side panel step 3)
  2646. if (message.payload.email) {
  2647. await setEmailState(message.payload.email);
  2648. }
  2649. if (message.payload.emailPrefix !== undefined) {
  2650. await setPersistentSettings({ emailPrefix: message.payload.emailPrefix });
  2651. await setState({ emailPrefix: message.payload.emailPrefix });
  2652. }
  2653. if (doesStepUseCompletionSignal(step)) {
  2654. await executeStepViaCompletionSignal(step);
  2655. } else {
  2656. await executeStep(step);
  2657. }
  2658. return { ok: true };
  2659. }
  2660. case 'AUTO_RUN': {
  2661. clearStopRequest();
  2662. const state = await getState();
  2663. if (isAutoRunScheduledState(state)) {
  2664. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  2665. }
  2666. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  2667. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  2668. const mode = message.payload?.mode === 'continue' ? 'continue' : 'restart';
  2669. await setState({ autoRunSkipFailures });
  2670. startAutoRunLoop(totalRuns, { autoRunSkipFailures, mode });
  2671. return { ok: true };
  2672. }
  2673. case 'SCHEDULE_AUTO_RUN': {
  2674. clearStopRequest();
  2675. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  2676. return await scheduleAutoRun(totalRuns, {
  2677. delayMinutes: message.payload?.delayMinutes,
  2678. autoRunSkipFailures: Boolean(message.payload?.autoRunSkipFailures),
  2679. mode: message.payload?.mode,
  2680. });
  2681. }
  2682. case 'START_SCHEDULED_AUTO_RUN_NOW': {
  2683. clearStopRequest();
  2684. const started = await launchScheduledAutoRun('manual');
  2685. if (!started) {
  2686. throw new Error('当前没有可立即开始的倒计时计划。');
  2687. }
  2688. return { ok: true };
  2689. }
  2690. case 'CANCEL_SCHEDULED_AUTO_RUN': {
  2691. const cancelled = await cancelScheduledAutoRun();
  2692. if (!cancelled) {
  2693. throw new Error('当前没有可取消的倒计时计划。');
  2694. }
  2695. return { ok: true };
  2696. }
  2697. case 'SKIP_AUTO_RUN_COUNTDOWN': {
  2698. clearStopRequest();
  2699. const skipped = await skipAutoRunCountdown();
  2700. if (!skipped) {
  2701. throw new Error('当前没有可立即开始的倒计时。');
  2702. }
  2703. return { ok: true };
  2704. }
  2705. case 'RESUME_AUTO_RUN': {
  2706. clearStopRequest();
  2707. if (message.payload.email) {
  2708. await setEmailState(message.payload.email);
  2709. }
  2710. resumeAutoRun().catch((error) => {
  2711. handleAutoRunLoopUnhandledError(error).catch((handlerError) => {
  2712. console.error(LOG_PREFIX, 'Failed to finalize resume error:', handlerError);
  2713. });
  2714. });
  2715. return { ok: true };
  2716. }
  2717. case 'TAKEOVER_AUTO_RUN': {
  2718. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  2719. await addLog('自动流程已切换为手动控制。', 'warn');
  2720. return { ok: true };
  2721. }
  2722. case 'SKIP_STEP': {
  2723. const step = Number(message.payload?.step);
  2724. return await skipStep(step);
  2725. }
  2726. case 'SAVE_SETTING': {
  2727. const updates = buildPersistentSettingsPayload(message.payload || {});
  2728. await setPersistentSettings(updates);
  2729. await setState(updates);
  2730. return { ok: true, state: await getState() };
  2731. }
  2732. case 'EXPORT_SETTINGS': {
  2733. return { ok: true, ...(await exportSettingsBundle()) };
  2734. }
  2735. case 'IMPORT_SETTINGS': {
  2736. const state = await importSettingsBundle(message.payload?.config || null);
  2737. return { ok: true, state };
  2738. }
  2739. case 'UPSERT_HOTMAIL_ACCOUNT': {
  2740. const account = await upsertHotmailAccount(message.payload || {});
  2741. return { ok: true, account };
  2742. }
  2743. case 'DELETE_HOTMAIL_ACCOUNT': {
  2744. await deleteHotmailAccount(String(message.payload?.accountId || ''));
  2745. return { ok: true };
  2746. }
  2747. case 'DELETE_HOTMAIL_ACCOUNTS': {
  2748. const result = await deleteHotmailAccounts(String(message.payload?.mode || 'all'));
  2749. return { ok: true, ...result };
  2750. }
  2751. case 'SELECT_HOTMAIL_ACCOUNT': {
  2752. const account = await setCurrentHotmailAccount(String(message.payload?.accountId || ''), {
  2753. markUsed: false,
  2754. syncEmail: true,
  2755. });
  2756. return { ok: true, account };
  2757. }
  2758. case 'PATCH_HOTMAIL_ACCOUNT': {
  2759. const account = await patchHotmailAccount(
  2760. String(message.payload?.accountId || ''),
  2761. message.payload?.updates || {}
  2762. );
  2763. return { ok: true, account };
  2764. }
  2765. case 'VERIFY_HOTMAIL_ACCOUNT':
  2766. case 'AUTHORIZE_HOTMAIL_ACCOUNT': {
  2767. const accountId = String(message.payload?.accountId || '');
  2768. try {
  2769. const result = await verifyHotmailAccount(accountId);
  2770. await setCurrentHotmailAccount(result.account.id, { markUsed: false, syncEmail: true });
  2771. await addLog(`Hotmail 账号 ${result.account.email} 校验通过,可直接用于收信。`, 'ok');
  2772. return { ok: true, account: result.account, messageCount: result.messageCount };
  2773. } catch (err) {
  2774. const state = await getState();
  2775. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  2776. const target = findHotmailAccount(accounts, accountId);
  2777. if (target) {
  2778. target.status = 'error';
  2779. target.lastError = err.message;
  2780. await syncHotmailAccounts(accounts.map((item) => (item.id === target.id ? target : item)));
  2781. }
  2782. throw err;
  2783. }
  2784. }
  2785. case 'TEST_HOTMAIL_ACCOUNT': {
  2786. const result = await testHotmailAccountMailAccess(String(message.payload?.accountId || ''));
  2787. return { ok: true, ...result };
  2788. }
  2789. // Side panel data updates
  2790. case 'SET_EMAIL_STATE': {
  2791. const state = await getState();
  2792. if (isAutoRunLockedState(state)) {
  2793. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  2794. }
  2795. const email = String(message.payload?.email || '').trim() || null;
  2796. await setEmailStateSilently(email);
  2797. return { ok: true, email };
  2798. }
  2799. case 'SAVE_EMAIL': {
  2800. const state = await getState();
  2801. if (isAutoRunLockedState(state)) {
  2802. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  2803. }
  2804. await setEmailState(message.payload.email);
  2805. await resumeAutoRun();
  2806. return { ok: true, email: message.payload.email };
  2807. }
  2808. case 'FETCH_GENERATED_EMAIL': {
  2809. clearStopRequest();
  2810. const state = await getState();
  2811. if (isAutoRunLockedState(state)) {
  2812. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  2813. }
  2814. const email = await fetchGeneratedEmail(state, message.payload || {});
  2815. await resumeAutoRun();
  2816. return { ok: true, email };
  2817. }
  2818. case 'FETCH_DUCK_EMAIL': {
  2819. clearStopRequest();
  2820. const state = await getState();
  2821. if (isAutoRunLockedState(state)) {
  2822. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  2823. }
  2824. const email = await fetchGeneratedEmail(state, { ...(message.payload || {}), generator: 'duck' });
  2825. await resumeAutoRun();
  2826. return { ok: true, email };
  2827. }
  2828. case 'STOP_FLOW': {
  2829. await requestStop();
  2830. return { ok: true };
  2831. }
  2832. default:
  2833. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  2834. return { error: `Unknown message type: ${message.type}` };
  2835. }
  2836. }
  2837. // ============================================================
  2838. // Step Data Handlers
  2839. // ============================================================
  2840. async function handleStepData(step, payload) {
  2841. switch (step) {
  2842. case 1: {
  2843. const updates = {};
  2844. if (payload.oauthUrl) {
  2845. updates.oauthUrl = payload.oauthUrl;
  2846. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  2847. }
  2848. if (payload.sub2apiSessionId !== undefined) updates.sub2apiSessionId = payload.sub2apiSessionId || null;
  2849. if (payload.sub2apiOAuthState !== undefined) updates.sub2apiOAuthState = payload.sub2apiOAuthState || null;
  2850. if (payload.sub2apiGroupId !== undefined) updates.sub2apiGroupId = payload.sub2apiGroupId || null;
  2851. if (payload.sub2apiDraftName !== undefined) updates.sub2apiDraftName = payload.sub2apiDraftName || null;
  2852. if (Object.keys(updates).length) {
  2853. await setState(updates);
  2854. }
  2855. break;
  2856. }
  2857. case 3:
  2858. if (payload.email) await setEmailState(payload.email);
  2859. if (payload.signupVerificationRequestedAt) {
  2860. await setState({ signupVerificationRequestedAt: payload.signupVerificationRequestedAt });
  2861. }
  2862. if (payload.loginVerificationRequestedAt) {
  2863. await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt });
  2864. }
  2865. break;
  2866. case 6:
  2867. if (payload.loginVerificationRequestedAt) {
  2868. await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt });
  2869. }
  2870. break;
  2871. case 4:
  2872. await setState({
  2873. lastEmailTimestamp: payload.emailTimestamp || null,
  2874. signupVerificationRequestedAt: null,
  2875. });
  2876. break;
  2877. case 7:
  2878. await setState({
  2879. lastEmailTimestamp: payload.emailTimestamp || null,
  2880. loginVerificationRequestedAt: null,
  2881. });
  2882. break;
  2883. case 8:
  2884. if (payload.localhostUrl) {
  2885. if (!isLocalhostOAuthCallbackUrl(payload.localhostUrl)) {
  2886. throw new Error('步骤 8 返回了无效的 localhost OAuth 回调地址。');
  2887. }
  2888. await setState({ localhostUrl: payload.localhostUrl });
  2889. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  2890. }
  2891. break;
  2892. case 9: {
  2893. if (payload.localhostUrl) {
  2894. await closeLocalhostCallbackTabs(payload.localhostUrl);
  2895. }
  2896. const latestState = await getState();
  2897. if (latestState.currentHotmailAccountId && isHotmailProvider(latestState)) {
  2898. await patchHotmailAccount(latestState.currentHotmailAccountId, {
  2899. used: true,
  2900. lastUsedAt: Date.now(),
  2901. });
  2902. await addLog('当前 Hotmail 账号已自动标记为已用。', 'ok');
  2903. }
  2904. const localhostPrefix = buildLocalhostCleanupPrefix(payload.localhostUrl);
  2905. if (localhostPrefix) {
  2906. await closeTabsByUrlPrefix(localhostPrefix, {
  2907. excludeUrls: [payload.localhostUrl],
  2908. excludeLocalhostCallbacks: true,
  2909. });
  2910. }
  2911. if (shouldUseCustomRegistrationEmail(latestState) && latestState.email) {
  2912. await setEmailStateSilently(null);
  2913. }
  2914. break;
  2915. }
  2916. }
  2917. }
  2918. // ============================================================
  2919. // Step Completion Waiting
  2920. // ============================================================
  2921. // Map of step -> { resolve, reject } for waiting on step completion
  2922. const stepWaiters = new Map();
  2923. let resumeWaiter = null;
  2924. const AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS = 120000;
  2925. const AUTO_RUN_BACKGROUND_COMPLETED_STEPS = new Set([4, 7, 8]);
  2926. const STEP_COMPLETION_SIGNAL_STEPS = new Set([1, 2, 3, 5, 6, 9]);
  2927. function waitForStepComplete(step, timeoutMs = 120000) {
  2928. return new Promise((resolve, reject) => {
  2929. throwIfStopped();
  2930. if (stepWaiters.has(step)) {
  2931. console.warn(LOG_PREFIX, `[waitForStepComplete] replacing existing waiter for step ${step}`);
  2932. }
  2933. console.log(LOG_PREFIX, `[waitForStepComplete] register step ${step}, timeout=${timeoutMs}ms`);
  2934. const timer = setTimeout(() => {
  2935. stepWaiters.delete(step);
  2936. console.warn(LOG_PREFIX, `[waitForStepComplete] timeout for step ${step} after ${timeoutMs}ms`);
  2937. reject(new Error(`步骤 ${step} 等待超时(>${timeoutMs / 1000} 秒)`));
  2938. }, timeoutMs);
  2939. stepWaiters.set(step, {
  2940. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  2941. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  2942. });
  2943. });
  2944. }
  2945. function doesStepUseCompletionSignal(step) {
  2946. return STEP_COMPLETION_SIGNAL_STEPS.has(step);
  2947. }
  2948. function notifyStepComplete(step, payload) {
  2949. const waiter = stepWaiters.get(step);
  2950. console.log(LOG_PREFIX, `[notifyStepComplete] step ${step}, hasWaiter=${Boolean(waiter)}`);
  2951. if (waiter) waiter.resolve(payload);
  2952. }
  2953. function notifyStepError(step, error) {
  2954. const waiter = stepWaiters.get(step);
  2955. console.warn(LOG_PREFIX, `[notifyStepError] step ${step}, hasWaiter=${Boolean(waiter)}, error=${error}`);
  2956. if (waiter) waiter.reject(new Error(error));
  2957. }
  2958. async function completeStepFromBackground(step, payload = {}) {
  2959. if (stopRequested) {
  2960. await setStepStatus(step, 'stopped');
  2961. notifyStepError(step, STOP_ERROR_MESSAGE);
  2962. return;
  2963. }
  2964. await setStepStatus(step, 'completed');
  2965. await addLog(`步骤 ${step} 已完成`, 'ok');
  2966. await handleStepData(step, payload);
  2967. notifyStepComplete(step, payload);
  2968. }
  2969. async function finalizeDeferredStepExecutionError(step, error) {
  2970. const latestState = await getState();
  2971. const currentStatus = latestState.stepStatuses?.[step];
  2972. if (currentStatus === 'completed' || currentStatus === 'failed' || currentStatus === 'stopped') {
  2973. return;
  2974. }
  2975. if (isStopError(error)) {
  2976. await setStepStatus(step, 'stopped');
  2977. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  2978. return;
  2979. }
  2980. await setStepStatus(step, 'failed');
  2981. await addLog(`步骤 ${step} 失败:${getErrorMessage(error)}`, 'error');
  2982. }
  2983. async function executeStepViaCompletionSignal(step, timeoutMs = AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS) {
  2984. const completionResultPromise = waitForStepComplete(step, timeoutMs).then(
  2985. payload => ({ ok: true, payload }),
  2986. error => ({ ok: false, error }),
  2987. );
  2988. let executeError = null;
  2989. try {
  2990. await executeStep(step, { deferRetryableTransportError: true });
  2991. } catch (err) {
  2992. executeError = err;
  2993. if (isStopError(err) || !isRetryableContentScriptTransportError(err)) {
  2994. notifyStepError(step, getErrorMessage(err));
  2995. }
  2996. }
  2997. const completionResult = await completionResultPromise;
  2998. if (completionResult.ok) {
  2999. if (executeError) {
  3000. console.warn(
  3001. LOG_PREFIX,
  3002. `[executeStepViaCompletionSignal] step ${step} completed after deferred execute error: ${getErrorMessage(executeError)}`
  3003. );
  3004. }
  3005. return completionResult.payload;
  3006. }
  3007. if (executeError && isRetryableContentScriptTransportError(executeError)) {
  3008. const completionMessage = getErrorMessage(completionResult.error);
  3009. if (/等待超时/.test(completionMessage)) {
  3010. await finalizeDeferredStepExecutionError(step, executeError);
  3011. throw executeError;
  3012. }
  3013. throw completionResult.error;
  3014. }
  3015. if (executeError) {
  3016. throw executeError;
  3017. }
  3018. throw completionResult.error;
  3019. }
  3020. async function waitForRunningStepsToFinish(payload = {}) {
  3021. let currentState = await getState();
  3022. let runningSteps = getRunningSteps(currentState.stepStatuses);
  3023. if (!runningSteps.length) {
  3024. return currentState;
  3025. }
  3026. await addLog(`自动继续:检测到步骤 ${runningSteps.join(', ')} 正在运行,等待完成后再继续自动流程...`, 'info');
  3027. await broadcastAutoRunStatus('waiting_step', payload);
  3028. while (runningSteps.length) {
  3029. await sleepWithStop(250);
  3030. currentState = await getState();
  3031. runningSteps = getRunningSteps(currentState.stepStatuses);
  3032. }
  3033. await addLog('自动继续:当前运行步骤已结束,准备按最新进度继续自动流程...', 'info');
  3034. return currentState;
  3035. }
  3036. async function markRunningStepsStopped() {
  3037. const state = await getState();
  3038. const runningSteps = getRunningSteps(state.stepStatuses);
  3039. for (const step of runningSteps) {
  3040. await setStepStatus(step, 'stopped');
  3041. }
  3042. }
  3043. async function requestStop(options = {}) {
  3044. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  3045. const state = await getState();
  3046. if (isAutoRunScheduledState(state) && !autoRunActive) {
  3047. await cancelScheduledAutoRun({
  3048. logMessage: options.logMessage === false
  3049. ? false
  3050. : (options.logMessage || '已取消自动运行倒计时计划。'),
  3051. });
  3052. return;
  3053. }
  3054. if (stopRequested) return;
  3055. stopRequested = true;
  3056. cancelPendingCommands();
  3057. cleanupStep8NavigationListeners();
  3058. rejectPendingStep8(new Error(STOP_ERROR_MESSAGE));
  3059. await addLog(logMessage, 'warn');
  3060. await broadcastStopToContentScripts();
  3061. for (const waiter of stepWaiters.values()) {
  3062. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  3063. }
  3064. stepWaiters.clear();
  3065. if (resumeWaiter) {
  3066. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  3067. resumeWaiter = null;
  3068. }
  3069. await markRunningStepsStopped();
  3070. autoRunActive = false;
  3071. await broadcastAutoRunStatus('stopped', {
  3072. currentRun: autoRunCurrentRun,
  3073. totalRuns: autoRunTotalRuns,
  3074. attemptRun: autoRunAttemptRun,
  3075. });
  3076. }
  3077. // ============================================================
  3078. // Step Execution
  3079. // ============================================================
  3080. async function executeStep(step, options = {}) {
  3081. const { deferRetryableTransportError = false } = options;
  3082. console.log(LOG_PREFIX, `Executing step ${step}`);
  3083. throwIfStopped();
  3084. await setStepStatus(step, 'running');
  3085. await addLog(`步骤 ${step} 开始执行`);
  3086. await humanStepDelay();
  3087. const state = await getState();
  3088. // Set flow start time on first step
  3089. if (step === 1 && !state.flowStartTime) {
  3090. await setState({ flowStartTime: Date.now() });
  3091. }
  3092. try {
  3093. switch (step) {
  3094. case 1: await executeStep1(state); break;
  3095. case 2: await executeStep2(state); break;
  3096. case 3: await executeStep3(state); break;
  3097. case 4: await executeStep4(state); break;
  3098. case 5: await executeStep5(state); break;
  3099. case 6: await executeStep6(state); break;
  3100. case 7: await executeStep7(state); break;
  3101. case 8: await executeStep8(state); break;
  3102. case 9: await executeStep9(state); break;
  3103. default:
  3104. throw new Error(`未知步骤:${step}`);
  3105. }
  3106. } catch (err) {
  3107. if (isStopError(err)) {
  3108. await setStepStatus(step, 'stopped');
  3109. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  3110. throw err;
  3111. }
  3112. if (!(deferRetryableTransportError && doesStepUseCompletionSignal(step) && isRetryableContentScriptTransportError(err))) {
  3113. await setStepStatus(step, 'failed');
  3114. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  3115. } else {
  3116. console.warn(
  3117. LOG_PREFIX,
  3118. `[executeStep] deferring retryable transport error for step ${step}: ${getErrorMessage(err)}`
  3119. );
  3120. }
  3121. throw err;
  3122. }
  3123. }
  3124. /**
  3125. * Execute a step and wait for it to complete before returning.
  3126. * @param {number} step
  3127. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  3128. */
  3129. async function executeStepAndWait(step, delayAfter = 2000) {
  3130. throwIfStopped();
  3131. const delaySeconds = normalizeAutoStepDelaySeconds((await getState()).autoStepDelaySeconds, null);
  3132. if (delaySeconds > 0) {
  3133. await addLog(
  3134. `自动运行:步骤 ${step} 执行前额外等待 ${delaySeconds} 秒,避免节奏过快。`,
  3135. 'info'
  3136. );
  3137. await sleepWithStop(delaySeconds * 1000);
  3138. }
  3139. if (AUTO_RUN_BACKGROUND_COMPLETED_STEPS.has(step)) {
  3140. await addLog(`自动运行:步骤 ${step} 由后台流程负责收尾,执行函数返回后将直接进入下一步。`, 'info');
  3141. await executeStep(step);
  3142. const latestState = await getState();
  3143. await addLog(`自动运行:步骤 ${step} 已执行返回,当前状态为 ${latestState.stepStatuses?.[step] || 'pending'},准备继续后续步骤。`, 'info');
  3144. } else if (doesStepUseCompletionSignal(step)) {
  3145. await addLog(`自动运行:步骤 ${step} 已发起,正在等待完成信号(超时 ${AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS / 1000} 秒)。`, 'info');
  3146. await executeStepViaCompletionSignal(step, AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS);
  3147. await addLog(`自动运行:步骤 ${step} 已收到完成信号,准备继续后续步骤。`, 'info');
  3148. } else {
  3149. await executeStep(step);
  3150. }
  3151. // Extra delay for page transitions / DOM updates
  3152. if (delayAfter > 0) {
  3153. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  3154. }
  3155. }
  3156. function getEmailGeneratorLabel(generator) {
  3157. if (generator === 'custom') {
  3158. return '自定义邮箱';
  3159. }
  3160. if (generator === 'cloudflare') return 'Cloudflare 邮箱';
  3161. if (generator === CLOUDFLARE_TEMP_EMAIL_GENERATOR) return 'Cloudflare Temp Email';
  3162. return 'Duck 邮箱';
  3163. }
  3164. function generateCloudflareAliasLocalPart() {
  3165. const letters = 'abcdefghijklmnopqrstuvwxyz';
  3166. const digits = '0123456789';
  3167. const chars = [];
  3168. for (let i = 0; i < 6; i++) {
  3169. chars.push(letters[Math.floor(Math.random() * letters.length)]);
  3170. }
  3171. for (let i = 0; i < 4; i++) {
  3172. chars.push(digits[Math.floor(Math.random() * digits.length)]);
  3173. }
  3174. for (let i = chars.length - 1; i > 0; i--) {
  3175. const j = Math.floor(Math.random() * (i + 1));
  3176. [chars[i], chars[j]] = [chars[j], chars[i]];
  3177. }
  3178. return chars.join('');
  3179. }
  3180. async function fetchCloudflareEmail(state, options = {}) {
  3181. throwIfStopped();
  3182. const latestState = state || await getState();
  3183. const domain = normalizeCloudflareDomain(latestState.cloudflareDomain);
  3184. if (!domain) {
  3185. throw new Error('Cloudflare 域名为空或格式无效。');
  3186. }
  3187. const localPart = String(options.localPart || '').trim().toLowerCase() || generateCloudflareAliasLocalPart();
  3188. const aliasEmail = `${localPart}@${domain}`;
  3189. await setEmailState(aliasEmail);
  3190. await addLog(`Cloudflare 邮箱:已生成 ${aliasEmail}`, 'ok');
  3191. return aliasEmail;
  3192. }
  3193. function ensureCloudflareTempEmailConfig(state, options = {}) {
  3194. const {
  3195. requireAdminAuth = false,
  3196. requireDomain = false,
  3197. } = options;
  3198. const config = getCloudflareTempEmailConfig(state);
  3199. if (!config.baseUrl) {
  3200. throw new Error('Cloudflare Temp Email 服务地址为空或格式无效。');
  3201. }
  3202. if (requireAdminAuth && !config.adminAuth) {
  3203. throw new Error('Cloudflare Temp Email 缺少 Admin Auth。');
  3204. }
  3205. if (requireDomain && !config.domain) {
  3206. throw new Error('Cloudflare Temp Email 域名为空或格式无效。');
  3207. }
  3208. return config;
  3209. }
  3210. async function requestCloudflareTempEmailJson(config, path, options = {}) {
  3211. const {
  3212. method = 'GET',
  3213. payload,
  3214. searchParams,
  3215. timeoutMs = 20000,
  3216. } = options;
  3217. const url = new URL(joinCloudflareTempEmailUrl(config.baseUrl, path));
  3218. if (searchParams && typeof searchParams === 'object') {
  3219. for (const [key, value] of Object.entries(searchParams)) {
  3220. if (value === undefined || value === null || value === '') continue;
  3221. url.searchParams.set(key, String(value));
  3222. }
  3223. }
  3224. const controller = new AbortController();
  3225. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
  3226. let response;
  3227. try {
  3228. response = await fetch(url.toString(), {
  3229. method,
  3230. headers: buildCloudflareTempEmailHeaders(config, {
  3231. json: payload !== undefined,
  3232. }),
  3233. body: payload !== undefined ? JSON.stringify(payload) : undefined,
  3234. signal: controller.signal,
  3235. });
  3236. } catch (err) {
  3237. const errorMessage = err?.name === 'AbortError'
  3238. ? `Cloudflare Temp Email 请求超时(>${Math.round(timeoutMs / 1000)} 秒)`
  3239. : `Cloudflare Temp Email 请求失败:${err.message}`;
  3240. throw new Error(errorMessage);
  3241. } finally {
  3242. clearTimeout(timeoutId);
  3243. }
  3244. const text = await response.text();
  3245. let parsed;
  3246. try {
  3247. parsed = text ? JSON.parse(text) : {};
  3248. } catch {
  3249. parsed = text;
  3250. }
  3251. if (!response.ok) {
  3252. const payloadError = typeof parsed === 'object' && parsed
  3253. ? (parsed.message || parsed.error || parsed.msg)
  3254. : '';
  3255. throw new Error(`Cloudflare Temp Email 请求失败:${payloadError || text || `HTTP ${response.status}`}`);
  3256. }
  3257. return parsed;
  3258. }
  3259. async function fetchCloudflareTempEmailAddress(state, options = {}) {
  3260. throwIfStopped();
  3261. const latestState = state || await getState();
  3262. const config = ensureCloudflareTempEmailConfig(latestState, {
  3263. requireAdminAuth: true,
  3264. requireDomain: true,
  3265. });
  3266. const requestedName = String(options.localPart || options.name || '').trim().toLowerCase() || generateCloudflareAliasLocalPart();
  3267. const payload = {
  3268. enablePrefix: true,
  3269. name: requestedName,
  3270. domain: config.domain,
  3271. };
  3272. const result = await requestCloudflareTempEmailJson(config, '/admin/new_address', {
  3273. method: 'POST',
  3274. payload,
  3275. });
  3276. const address = normalizeCloudflareTempEmailAddress(getCloudflareTempEmailAddressFromResponse(result));
  3277. if (!address) {
  3278. throw new Error('Cloudflare Temp Email 未返回可用邮箱地址。');
  3279. }
  3280. await setEmailState(address);
  3281. await addLog(`Cloudflare Temp Email:已生成 ${address}`, 'ok');
  3282. return address;
  3283. }
  3284. async function fetchDuckEmail(options = {}) {
  3285. throwIfStopped();
  3286. const { generateNew = true } = options;
  3287. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  3288. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  3289. const result = await sendToContentScript('duck-mail', {
  3290. type: 'FETCH_DUCK_EMAIL',
  3291. source: 'background',
  3292. payload: { generateNew },
  3293. });
  3294. if (result?.error) {
  3295. throw new Error(result.error);
  3296. }
  3297. if (!result?.email) {
  3298. throw new Error('未返回 Duck 邮箱地址。');
  3299. }
  3300. await setEmailState(result.email);
  3301. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  3302. return result.email;
  3303. }
  3304. async function fetchGeneratedEmail(state, options = {}) {
  3305. const currentState = state || await getState();
  3306. const generator = normalizeEmailGenerator(options.generator ?? currentState.emailGenerator);
  3307. if (generator === 'custom') {
  3308. throw new Error('当前邮箱生成方式为自定义邮箱,请直接填写注册邮箱。');
  3309. }
  3310. if (generator === 'cloudflare') {
  3311. return fetchCloudflareEmail(currentState, options);
  3312. }
  3313. if (generator === CLOUDFLARE_TEMP_EMAIL_GENERATOR) {
  3314. return fetchCloudflareTempEmailAddress(currentState, options);
  3315. }
  3316. return fetchDuckEmail(options);
  3317. }
  3318. // ============================================================
  3319. // Auto Run Flow
  3320. // ============================================================
  3321. let autoRunActive = false;
  3322. let autoRunCurrentRun = 0;
  3323. let autoRunTotalRuns = 1;
  3324. let autoRunAttemptRun = 0;
  3325. const EMAIL_FETCH_MAX_ATTEMPTS = 5;
  3326. const VERIFICATION_POLL_MAX_ROUNDS = 5;
  3327. const STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS = 25000;
  3328. const AUTO_STEP_DELAYS = {
  3329. 1: 2000,
  3330. 2: 2000,
  3331. 3: 3000,
  3332. 4: 2000,
  3333. 5: 3000,
  3334. 6: 3000,
  3335. 7: 2000,
  3336. 8: 2000,
  3337. 9: 1000,
  3338. };
  3339. async function resumeAutoRunIfWaitingForEmail(options = {}) {
  3340. const { silent = false } = options;
  3341. const state = await getState();
  3342. if (!state.email || !isAutoRunPausedState(state)) {
  3343. return false;
  3344. }
  3345. if (resumeWaiter) {
  3346. if (!silent) {
  3347. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  3348. }
  3349. resumeWaiter.resolve();
  3350. resumeWaiter = null;
  3351. return true;
  3352. }
  3353. return false;
  3354. }
  3355. async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
  3356. const currentState = await getState();
  3357. if (isHotmailProvider(currentState)) {
  3358. const account = await ensureHotmailAccountForFlow({
  3359. allowAllocate: true,
  3360. markUsed: true,
  3361. preferredAccountId: null,
  3362. });
  3363. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:已分配 Hotmail 账号 ${account.email}(第 ${attemptRuns} 次尝试)===`, 'ok');
  3364. return account.email;
  3365. }
  3366. if (isGeneratedAliasProvider(currentState.mailProvider)) {
  3367. if (!currentState.emailPrefix) {
  3368. throw new Error('2925 邮箱前缀未设置,请先在侧边栏填写。');
  3369. }
  3370. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:2925 模式已启用,将在步骤 3 自动生成邮箱(第 ${attemptRuns} 次尝试)===`, 'info');
  3371. return null;
  3372. }
  3373. if (currentState.email) {
  3374. return currentState.email;
  3375. }
  3376. if (shouldUseCustomRegistrationEmail(currentState)) {
  3377. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先填写自定义注册邮箱,然后继续 ===`, 'warn');
  3378. await broadcastAutoRunStatus('waiting_email', {
  3379. currentRun: targetRun,
  3380. totalRuns,
  3381. attemptRun: attemptRuns,
  3382. });
  3383. await waitForResume();
  3384. const resumedState = await getState();
  3385. if (!resumedState.email) {
  3386. throw new Error('无法继续:当前没有注册邮箱。');
  3387. }
  3388. return resumedState.email;
  3389. }
  3390. const generator = normalizeEmailGenerator(currentState.emailGenerator);
  3391. const generatorLabel = getEmailGeneratorLabel(generator);
  3392. let lastError = null;
  3393. for (let attempt = 1; attempt <= EMAIL_FETCH_MAX_ATTEMPTS; attempt++) {
  3394. try {
  3395. if (attempt > 1) {
  3396. await addLog(`${generatorLabel}:正在进行第 ${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS} 次自动获取重试...`, 'warn');
  3397. }
  3398. const generatedEmail = await fetchGeneratedEmail(currentState, { generateNew: true, generator });
  3399. await addLog(
  3400. `=== 目标 ${targetRun}/${totalRuns} 轮:${generatorLabel}已就绪:${generatedEmail}(第 ${attemptRuns} 次尝试,第 ${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS} 次获取)===`,
  3401. 'ok'
  3402. );
  3403. return generatedEmail;
  3404. } catch (err) {
  3405. lastError = err;
  3406. await addLog(`${generatorLabel}自动获取失败(${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS}):${err.message}`, 'warn');
  3407. if (
  3408. (generator === 'cloudflare' && /域名/.test(String(err.message || '')))
  3409. || (generator === CLOUDFLARE_TEMP_EMAIL_GENERATOR && /(服务地址|Admin Auth|域名)/.test(String(err.message || '')))
  3410. ) {
  3411. break;
  3412. }
  3413. }
  3414. }
  3415. await addLog(`${generatorLabel}自动获取已连续失败 ${EMAIL_FETCH_MAX_ATTEMPTS} 次:${lastError?.message || '未知错误'}`, 'error');
  3416. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先自动获取邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  3417. await broadcastAutoRunStatus('waiting_email', {
  3418. currentRun: targetRun,
  3419. totalRuns,
  3420. attemptRun: attemptRuns,
  3421. });
  3422. await waitForResume();
  3423. const resumedState = await getState();
  3424. if (!resumedState.email) {
  3425. throw new Error('无法继续:当前没有邮箱地址。');
  3426. }
  3427. return resumedState.email;
  3428. }
  3429. async function runAutoSequenceFromStep(startStep, context = {}) {
  3430. const { targetRun, totalRuns, attemptRuns, continued = false } = context;
  3431. const maxStep9RestartAttempts = 5;
  3432. let step9RestartAttempts = 0;
  3433. if (continued) {
  3434. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续当前进度,从步骤 ${startStep} 开始(第 ${attemptRuns} 次尝试)===`, 'info');
  3435. } else {
  3436. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  3437. }
  3438. if (startStep <= 2) {
  3439. for (const step of [1, 2]) {
  3440. if (step < startStep) continue;
  3441. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  3442. }
  3443. }
  3444. if (startStep <= 3) {
  3445. await ensureAutoEmailReady(targetRun, totalRuns, attemptRuns);
  3446. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  3447. await broadcastAutoRunStatus('running', {
  3448. currentRun: targetRun,
  3449. totalRuns,
  3450. attemptRun: attemptRuns,
  3451. });
  3452. await executeStepAndWait(3, AUTO_STEP_DELAYS[3]);
  3453. } else {
  3454. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续执行剩余流程(第 ${attemptRuns} 次尝试)===`, 'info');
  3455. }
  3456. const signupTabId = await getTabId('signup-page');
  3457. if (signupTabId) {
  3458. await chrome.tabs.update(signupTabId, { active: true });
  3459. }
  3460. let step = Math.max(startStep, 4);
  3461. while (step <= 9) {
  3462. try {
  3463. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  3464. step += 1;
  3465. } catch (err) {
  3466. const latestState = await getState();
  3467. const currentMail = getMailConfig(latestState);
  3468. const shouldRetryStep9 = step === 9
  3469. && (
  3470. isLegacyStep9RecoverableAuthError(err)
  3471. || (currentMail.provider === HOTMAIL_PROVIDER && isStep9RecoverableAuthError(err))
  3472. )
  3473. && step9RestartAttempts < maxStep9RestartAttempts;
  3474. if (shouldRetryStep9) {
  3475. step9RestartAttempts += 1;
  3476. await addLog(
  3477. `步骤 9:检测到 CPA 认证失败,正在回到步骤 6 重新开始授权流程(${step9RestartAttempts}/${maxStep9RestartAttempts})...`,
  3478. 'warn'
  3479. );
  3480. await invalidateDownstreamAfterStepRestart(6, {
  3481. logLabel: `步骤 9 认证失败后准备回到步骤 6 重试(${step9RestartAttempts}/${maxStep9RestartAttempts})`,
  3482. });
  3483. step = 6;
  3484. continue;
  3485. }
  3486. throw err;
  3487. }
  3488. }
  3489. }
  3490. // Outer loop: keep retrying until the target number of successful runs is reached.
  3491. async function legacyAutoRunLoop(totalRuns, options = {}) {
  3492. if (autoRunActive) {
  3493. await addLog('自动运行已在进行中', 'warn');
  3494. return;
  3495. }
  3496. clearStopRequest();
  3497. autoRunActive = true;
  3498. autoRunTotalRuns = totalRuns;
  3499. autoRunCurrentRun = 0;
  3500. autoRunAttemptRun = 0;
  3501. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  3502. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  3503. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) ? options.resumeCurrentRun : 0;
  3504. const resumeSuccessfulRuns = Number.isInteger(options.resumeSuccessfulRuns) ? options.resumeSuccessfulRuns : 0;
  3505. const resumeAttemptRunsProcessed = Number.isInteger(options.resumeAttemptRunsProcessed) ? options.resumeAttemptRunsProcessed : 0;
  3506. let maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  3507. const forcedRetryCap = Math.max(totalRuns * 10, totalRuns + 20);
  3508. let successfulRuns = Math.max(0, resumeSuccessfulRuns);
  3509. let attemptRuns = Math.max(0, resumeAttemptRunsProcessed);
  3510. let forceFreshTabsNextRun = false;
  3511. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  3512. const initialState = await getState();
  3513. const initialPhase = continueCurrentOnFirstAttempt && getRunningSteps(initialState.stepStatuses).length
  3514. ? 'waiting_step'
  3515. : 'running';
  3516. await setState({
  3517. autoRunSkipFailures,
  3518. ...getAutoRunStatusPayload(initialPhase, {
  3519. currentRun: resumeCurrentRun,
  3520. totalRuns,
  3521. attemptRun: resumeAttemptRunsProcessed,
  3522. }),
  3523. });
  3524. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  3525. attemptRuns += 1;
  3526. const targetRun = successfulRuns + 1;
  3527. autoRunCurrentRun = targetRun;
  3528. autoRunAttemptRun = attemptRuns;
  3529. let startStep = 1;
  3530. let useExistingProgress = false;
  3531. if (continueCurrentOnFirstAttempt) {
  3532. let currentState = await getState();
  3533. if (getRunningSteps(currentState.stepStatuses).length) {
  3534. currentState = await waitForRunningStepsToFinish({
  3535. currentRun: targetRun,
  3536. totalRuns,
  3537. attemptRun: attemptRuns,
  3538. });
  3539. }
  3540. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  3541. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  3542. startStep = resumeStep;
  3543. useExistingProgress = true;
  3544. } else if (hasSavedProgress(currentState.stepStatuses)) {
  3545. await addLog('当前流程已全部处理,将按“重新开始”新开一轮自动运行。', 'info');
  3546. }
  3547. continueCurrentOnFirstAttempt = false;
  3548. }
  3549. if (!useExistingProgress) {
  3550. // Reset everything at the start of each fresh attempt (keep user settings).
  3551. const prevState = await getState();
  3552. const keepSettings = {
  3553. vpsUrl: prevState.vpsUrl,
  3554. vpsPassword: prevState.vpsPassword,
  3555. customPassword: prevState.customPassword,
  3556. autoRunSkipFailures: prevState.autoRunSkipFailures,
  3557. autoRunFallbackThreadIntervalMinutes: prevState.autoRunFallbackThreadIntervalMinutes,
  3558. autoRunDelayEnabled: prevState.autoRunDelayEnabled,
  3559. autoRunDelayMinutes: prevState.autoRunDelayMinutes,
  3560. autoStepDelaySeconds: prevState.autoStepDelaySeconds,
  3561. mailProvider: prevState.mailProvider,
  3562. emailGenerator: prevState.emailGenerator,
  3563. emailPrefix: prevState.emailPrefix,
  3564. inbucketHost: prevState.inbucketHost,
  3565. inbucketMailbox: prevState.inbucketMailbox,
  3566. cloudflareDomain: prevState.cloudflareDomain,
  3567. cloudflareDomains: prevState.cloudflareDomains,
  3568. // Fresh attempts must drop stale tab/url runtime state from the prior run.
  3569. tabRegistry: {},
  3570. sourceLastUrls: {},
  3571. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  3572. };
  3573. await resetState();
  3574. await setState(keepSettings);
  3575. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => { });
  3576. await sleepWithStop(500);
  3577. } else {
  3578. await setState({
  3579. autoRunSkipFailures,
  3580. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  3581. });
  3582. }
  3583. if (forceFreshTabsNextRun) {
  3584. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  3585. forceFreshTabsNextRun = false;
  3586. }
  3587. try {
  3588. throwIfStopped();
  3589. await broadcastAutoRunStatus('running', {
  3590. currentRun: targetRun,
  3591. totalRuns,
  3592. attemptRun: attemptRuns,
  3593. });
  3594. await runAutoSequenceFromStep(startStep, {
  3595. targetRun,
  3596. totalRuns,
  3597. attemptRuns,
  3598. continued: useExistingProgress,
  3599. });
  3600. successfulRuns += 1;
  3601. autoRunCurrentRun = successfulRuns;
  3602. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  3603. const fallbackThreadIntervalMinutes = normalizeAutoRunFallbackThreadIntervalMinutes(
  3604. (await getState()).autoRunFallbackThreadIntervalMinutes
  3605. );
  3606. if (autoRunSkipFailures && totalRuns > 1 && successfulRuns < totalRuns && fallbackThreadIntervalMinutes > 0) {
  3607. await addLog(
  3608. `兜底模式:第 ${successfulRuns}/${totalRuns} 轮已完成,等待 ${fallbackThreadIntervalMinutes} 分钟后再启动下一轮新线程。`,
  3609. 'info'
  3610. );
  3611. await sleepWithStop(fallbackThreadIntervalMinutes * 60 * 1000);
  3612. }
  3613. continue;
  3614. } catch (err) {
  3615. if (isStopError(err)) {
  3616. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  3617. await broadcastAutoRunStatus('stopped', {
  3618. currentRun: targetRun,
  3619. totalRuns,
  3620. attemptRun: attemptRuns,
  3621. });
  3622. break;
  3623. }
  3624. if (isRestartCurrentAttemptError(err)) {
  3625. await addLog(`目标 ${targetRun}/${totalRuns} 轮检测到当前邮箱已存在,当前线程已放弃,将重新开始新一轮。`, 'warn');
  3626. cancelPendingCommands('当前线程因邮箱已存在而放弃。');
  3627. await broadcastStopToContentScripts();
  3628. await broadcastAutoRunStatus('retrying', {
  3629. currentRun: targetRun,
  3630. totalRuns,
  3631. attemptRun: attemptRuns,
  3632. });
  3633. forceFreshTabsNextRun = true;
  3634. maxAttempts = Math.max(maxAttempts, Math.min(forcedRetryCap, attemptRuns + 1));
  3635. continue;
  3636. }
  3637. if (!autoRunSkipFailures) {
  3638. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  3639. await broadcastAutoRunStatus('stopped', {
  3640. currentRun: targetRun,
  3641. totalRuns,
  3642. attemptRun: attemptRuns,
  3643. });
  3644. break;
  3645. }
  3646. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  3647. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  3648. cancelPendingCommands('当前尝试已放弃。');
  3649. await broadcastStopToContentScripts();
  3650. await broadcastAutoRunStatus('retrying', {
  3651. currentRun: targetRun,
  3652. totalRuns,
  3653. attemptRun: attemptRuns,
  3654. });
  3655. forceFreshTabsNextRun = true;
  3656. }
  3657. }
  3658. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  3659. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  3660. await broadcastAutoRunStatus('stopped', {
  3661. currentRun: successfulRuns,
  3662. totalRuns: autoRunTotalRuns,
  3663. attemptRun: attemptRuns,
  3664. });
  3665. } else if (stopRequested) {
  3666. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  3667. await broadcastAutoRunStatus('stopped', {
  3668. currentRun: successfulRuns,
  3669. totalRuns: autoRunTotalRuns,
  3670. attemptRun: attemptRuns,
  3671. });
  3672. } else if (successfulRuns >= autoRunTotalRuns) {
  3673. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  3674. await broadcastAutoRunStatus('complete', {
  3675. currentRun: successfulRuns,
  3676. totalRuns: autoRunTotalRuns,
  3677. attemptRun: attemptRuns,
  3678. });
  3679. } else {
  3680. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  3681. await broadcastAutoRunStatus('stopped', {
  3682. currentRun: successfulRuns,
  3683. totalRuns: autoRunTotalRuns,
  3684. attemptRun: attemptRuns,
  3685. });
  3686. }
  3687. autoRunActive = false;
  3688. autoRunAttemptRun = attemptRuns;
  3689. await setState(getAutoRunStatusPayload(stopRequested ? 'stopped' : (successfulRuns >= autoRunTotalRuns ? 'complete' : 'stopped'), {
  3690. currentRun: successfulRuns,
  3691. totalRuns: autoRunTotalRuns,
  3692. attemptRun: attemptRuns,
  3693. }));
  3694. clearStopRequest();
  3695. }
  3696. async function waitForResume() {
  3697. throwIfStopped();
  3698. const state = await getState();
  3699. if (state.email) {
  3700. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  3701. return;
  3702. }
  3703. return new Promise((resolve, reject) => {
  3704. resumeWaiter = { resolve, reject };
  3705. });
  3706. }
  3707. async function legacyResumeAutoRun() {
  3708. throwIfStopped();
  3709. const state = await getState();
  3710. if (!state.email) {
  3711. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  3712. return false;
  3713. }
  3714. const resumedInMemory = await resumeAutoRunIfWaitingForEmail({ silent: true });
  3715. if (resumedInMemory) {
  3716. return true;
  3717. }
  3718. if (!isAutoRunPausedState(state)) {
  3719. return false;
  3720. }
  3721. if (autoRunActive) {
  3722. return false;
  3723. }
  3724. const totalRuns = state.autoRunTotalRuns || 1;
  3725. const currentRun = state.autoRunCurrentRun || 1;
  3726. const attemptRun = state.autoRunAttemptRun || 1;
  3727. const successfulRuns = Math.max(0, currentRun - 1);
  3728. await addLog('检测到自动流程暂停上下文已丢失,正在从当前进度恢复自动运行...', 'warn');
  3729. autoRunLoop(totalRuns, {
  3730. autoRunSkipFailures: Boolean(state.autoRunSkipFailures),
  3731. mode: 'continue',
  3732. resumeCurrentRun: currentRun,
  3733. resumeSuccessfulRuns: successfulRuns,
  3734. resumeAttemptRunsProcessed: Math.max(0, attemptRun - 1),
  3735. });
  3736. return true;
  3737. }
  3738. function createAutoRunRoundSummary(round) {
  3739. return {
  3740. round,
  3741. status: 'pending',
  3742. attempts: 0,
  3743. failureReasons: [],
  3744. finalFailureReason: '',
  3745. };
  3746. }
  3747. function normalizeAutoRunRoundSummary(summary, round) {
  3748. const base = createAutoRunRoundSummary(round);
  3749. if (!summary || typeof summary !== 'object') {
  3750. return base;
  3751. }
  3752. const status = String(summary.status || '').trim().toLowerCase();
  3753. return {
  3754. round,
  3755. status: ['pending', 'success', 'failed'].includes(status) ? status : base.status,
  3756. attempts: Math.max(0, Math.floor(Number(summary.attempts) || 0)),
  3757. failureReasons: Array.isArray(summary.failureReasons)
  3758. ? summary.failureReasons.map((item) => String(item || '').trim()).filter(Boolean)
  3759. : [],
  3760. finalFailureReason: String(summary.finalFailureReason || '').trim(),
  3761. };
  3762. }
  3763. function buildAutoRunRoundSummaries(totalRuns, rawSummaries = []) {
  3764. return Array.from({ length: totalRuns }, (_, index) => {
  3765. return normalizeAutoRunRoundSummary(rawSummaries[index], index + 1);
  3766. });
  3767. }
  3768. function serializeAutoRunRoundSummaries(totalRuns, roundSummaries = []) {
  3769. return buildAutoRunRoundSummaries(totalRuns, roundSummaries).map((summary) => ({
  3770. ...summary,
  3771. failureReasons: [...summary.failureReasons],
  3772. }));
  3773. }
  3774. function getAutoRunRoundRetryCount(summary) {
  3775. return Math.max(0, Number(summary?.attempts || 0) - 1);
  3776. }
  3777. function formatAutoRunFailureReasons(reasons = []) {
  3778. if (!Array.isArray(reasons) || !reasons.length) {
  3779. return '未知错误';
  3780. }
  3781. const counts = new Map();
  3782. for (const reason of reasons) {
  3783. const normalized = String(reason || '').trim() || '未知错误';
  3784. counts.set(normalized, (counts.get(normalized) || 0) + 1);
  3785. }
  3786. return Array.from(counts.entries())
  3787. .map(([reason, count]) => (count > 1 ? `${reason}(${count}次)` : reason))
  3788. .join(';');
  3789. }
  3790. async function logAutoRunFinalSummary(totalRuns, roundSummaries = []) {
  3791. const summaries = buildAutoRunRoundSummaries(totalRuns, roundSummaries);
  3792. const successRounds = summaries.filter((item) => item.status === 'success');
  3793. const failedRounds = summaries.filter((item) => item.status === 'failed');
  3794. const pendingRounds = summaries.filter((item) => item.status === 'pending');
  3795. await addLog('=== 自动运行汇总 ===', failedRounds.length ? 'warn' : 'ok');
  3796. await addLog(
  3797. `总轮数:${totalRuns};成功:${successRounds.length};失败:${failedRounds.length};未完成:${pendingRounds.length}`,
  3798. failedRounds.length ? 'warn' : 'ok'
  3799. );
  3800. if (successRounds.length) {
  3801. await addLog(
  3802. `成功轮次:${successRounds
  3803. .map((item) => `第 ${item.round} 轮(重试 ${getAutoRunRoundRetryCount(item)} 次)`)
  3804. .join(';')}`,
  3805. 'ok'
  3806. );
  3807. }
  3808. if (failedRounds.length) {
  3809. await addLog(
  3810. `失败轮次:${failedRounds
  3811. .map((item) => {
  3812. const retryCount = getAutoRunRoundRetryCount(item);
  3813. const finalReason = item.finalFailureReason || item.failureReasons[item.failureReasons.length - 1] || '未知错误';
  3814. const reasonSummary = formatAutoRunFailureReasons(item.failureReasons);
  3815. return `第 ${item.round} 轮(重试 ${retryCount} 次,最终原因:${finalReason};失败记录:${reasonSummary})`;
  3816. })
  3817. .join(';')}`,
  3818. 'error'
  3819. );
  3820. }
  3821. if (pendingRounds.length) {
  3822. await addLog(
  3823. `未完成轮次:${pendingRounds.map((item) => `第 ${item.round} 轮`).join(';')}`,
  3824. 'warn'
  3825. );
  3826. }
  3827. }
  3828. async function sleepWithAutoRunCountdown(waitMs, payload = {}) {
  3829. if (!Number.isFinite(waitMs) || waitMs <= 0) {
  3830. return;
  3831. }
  3832. autoRunCountdownSkipRequested = false;
  3833. const countdownPayload = {
  3834. ...payload,
  3835. countdownAt: Date.now() + waitMs,
  3836. };
  3837. await broadcastAutoRunStatus('waiting_interval', countdownPayload);
  3838. const start = Date.now();
  3839. try {
  3840. while (Date.now() - start < waitMs) {
  3841. throwIfStopped();
  3842. if (autoRunCountdownSkipRequested) {
  3843. autoRunCountdownSkipRequested = false;
  3844. return;
  3845. }
  3846. await new Promise((resolve) => setTimeout(resolve, Math.min(100, waitMs - (Date.now() - start))));
  3847. }
  3848. } finally {
  3849. if (!stopRequested) {
  3850. await broadcastAutoRunStatus('waiting_interval', {
  3851. ...payload,
  3852. countdownAt: null,
  3853. countdownTitle: '',
  3854. countdownNote: '',
  3855. });
  3856. }
  3857. }
  3858. }
  3859. async function skipAutoRunCountdown() {
  3860. const state = await getState();
  3861. if (!autoRunActive || state.autoRunPhase !== 'waiting_interval') {
  3862. return false;
  3863. }
  3864. autoRunCountdownSkipRequested = true;
  3865. await addLog('已手动跳过当前倒计时,自动流程将立即继续。', 'info');
  3866. await broadcastAutoRunStatus('waiting_interval', {
  3867. currentRun: state.autoRunCurrentRun,
  3868. totalRuns: state.autoRunTotalRuns,
  3869. attemptRun: state.autoRunAttemptRun,
  3870. countdownAt: null,
  3871. countdownTitle: '',
  3872. countdownNote: '',
  3873. });
  3874. return true;
  3875. }
  3876. async function waitBetweenAutoRunRounds(targetRun, totalRuns, roundSummary) {
  3877. if (totalRuns <= 1 || targetRun >= totalRuns) {
  3878. return;
  3879. }
  3880. const fallbackThreadIntervalMinutes = normalizeAutoRunFallbackThreadIntervalMinutes(
  3881. (await getState()).autoRunFallbackThreadIntervalMinutes
  3882. );
  3883. if (fallbackThreadIntervalMinutes <= 0) {
  3884. return;
  3885. }
  3886. const statusLabel = roundSummary?.status === 'failed' ? '失败' : '完成';
  3887. await addLog(
  3888. `线程间隔:第 ${targetRun}/${totalRuns} 轮已${statusLabel},等待 ${fallbackThreadIntervalMinutes} 分钟后开始下一轮。`,
  3889. 'info'
  3890. );
  3891. await sleepWithAutoRunCountdown(fallbackThreadIntervalMinutes * 60 * 1000, {
  3892. currentRun: targetRun,
  3893. totalRuns,
  3894. attemptRun: autoRunAttemptRun,
  3895. countdownTitle: '线程间隔中',
  3896. countdownNote: `第 ${Math.min(targetRun + 1, totalRuns)}/${totalRuns} 轮即将开始`,
  3897. });
  3898. }
  3899. async function waitBeforeAutoRunRetry(targetRun, totalRuns, nextAttemptRun) {
  3900. const fallbackThreadIntervalMinutes = normalizeAutoRunFallbackThreadIntervalMinutes(
  3901. (await getState()).autoRunFallbackThreadIntervalMinutes
  3902. );
  3903. if (fallbackThreadIntervalMinutes <= 0) {
  3904. return;
  3905. }
  3906. await addLog(
  3907. `线程间隔:等待 ${fallbackThreadIntervalMinutes} 分钟后开始第 ${targetRun}/${totalRuns} 轮第 ${nextAttemptRun} 次尝试。`,
  3908. 'info'
  3909. );
  3910. await sleepWithAutoRunCountdown(fallbackThreadIntervalMinutes * 60 * 1000, {
  3911. currentRun: targetRun,
  3912. totalRuns,
  3913. attemptRun: nextAttemptRun,
  3914. countdownTitle: '线程间隔中',
  3915. countdownNote: `第 ${targetRun}/${totalRuns} 轮第 ${nextAttemptRun} 次尝试即将开始`,
  3916. });
  3917. }
  3918. async function handleAutoRunLoopUnhandledError(error) {
  3919. console.error(LOG_PREFIX, 'Auto run loop crashed:', error);
  3920. if (!isStopError(error)) {
  3921. await addLog(`自动运行异常终止:${getErrorMessage(error) || '未知错误'}`, 'error');
  3922. }
  3923. autoRunActive = false;
  3924. await broadcastAutoRunStatus('stopped', {
  3925. currentRun: autoRunCurrentRun,
  3926. totalRuns: autoRunTotalRuns,
  3927. attemptRun: autoRunAttemptRun,
  3928. });
  3929. clearStopRequest();
  3930. }
  3931. function startAutoRunLoop(totalRuns, options = {}) {
  3932. autoRunLoop(totalRuns, options).catch((error) => {
  3933. handleAutoRunLoopUnhandledError(error).catch((handlerError) => {
  3934. console.error(LOG_PREFIX, 'Failed to finalize auto run error:', handlerError);
  3935. });
  3936. });
  3937. }
  3938. async function autoRunLoop(totalRuns, options = {}) {
  3939. if (autoRunActive) {
  3940. await addLog('自动运行已在进行中', 'warn');
  3941. return;
  3942. }
  3943. clearStopRequest();
  3944. autoRunActive = true;
  3945. autoRunTotalRuns = totalRuns;
  3946. autoRunCurrentRun = 0;
  3947. autoRunAttemptRun = 0;
  3948. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  3949. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  3950. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) && options.resumeCurrentRun > 0
  3951. ? Math.min(totalRuns, options.resumeCurrentRun)
  3952. : 1;
  3953. const resumeAttemptRun = Number.isInteger(options.resumeAttemptRun) && options.resumeAttemptRun > 0
  3954. ? Math.min(AUTO_RUN_MAX_RETRIES_PER_ROUND + 1, options.resumeAttemptRun)
  3955. : 1;
  3956. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  3957. let forceFreshTabsNextRun = false;
  3958. let stoppedEarly = false;
  3959. const roundSummaries = buildAutoRunRoundSummaries(totalRuns, options.resumeRoundSummaries);
  3960. if (continueCurrentOnFirstAttempt && resumeCurrentRun > 1) {
  3961. for (let round = 1; round < resumeCurrentRun; round += 1) {
  3962. const summary = roundSummaries[round - 1];
  3963. if (summary.status === 'pending') {
  3964. summary.status = 'success';
  3965. if (!summary.attempts) {
  3966. summary.attempts = 1;
  3967. }
  3968. }
  3969. }
  3970. }
  3971. let successfulRuns = roundSummaries.filter((item) => item.status === 'success').length;
  3972. const initialState = await getState();
  3973. const initialPhase = continueCurrentOnFirstAttempt && getRunningSteps(initialState.stepStatuses).length
  3974. ? 'waiting_step'
  3975. : 'running';
  3976. await setState({
  3977. autoRunSkipFailures,
  3978. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  3979. ...getAutoRunStatusPayload(initialPhase, {
  3980. currentRun: continueCurrentOnFirstAttempt ? resumeCurrentRun : 0,
  3981. totalRuns,
  3982. attemptRun: continueCurrentOnFirstAttempt ? resumeAttemptRun : 0,
  3983. }),
  3984. });
  3985. for (let targetRun = resumeCurrentRun; targetRun <= totalRuns; targetRun += 1) {
  3986. const roundSummary = roundSummaries[targetRun - 1];
  3987. const resumingCurrentRound = continueCurrentOnFirstAttempt && targetRun === resumeCurrentRun;
  3988. let attemptRun = resumingCurrentRound ? resumeAttemptRun : 1;
  3989. let reuseExistingProgress = resumingCurrentRound;
  3990. const maxAttemptsForRound = autoRunSkipFailures
  3991. ? AUTO_RUN_MAX_RETRIES_PER_ROUND + 1
  3992. : Math.max(1, attemptRun);
  3993. while (attemptRun <= maxAttemptsForRound) {
  3994. autoRunCurrentRun = targetRun;
  3995. autoRunAttemptRun = attemptRun;
  3996. roundSummary.attempts = attemptRun;
  3997. let startStep = 1;
  3998. let useExistingProgress = false;
  3999. if (reuseExistingProgress) {
  4000. let currentState = await getState();
  4001. if (getRunningSteps(currentState.stepStatuses).length) {
  4002. currentState = await waitForRunningStepsToFinish({
  4003. currentRun: targetRun,
  4004. totalRuns,
  4005. attemptRun,
  4006. });
  4007. }
  4008. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  4009. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  4010. startStep = resumeStep;
  4011. useExistingProgress = true;
  4012. } else if (hasSavedProgress(currentState.stepStatuses)) {
  4013. await addLog('检测到当前流程已处理完成,本轮将改为从步骤 1 重新开始。', 'info');
  4014. }
  4015. }
  4016. if (!useExistingProgress) {
  4017. const prevState = await getState();
  4018. const keepSettings = {
  4019. vpsUrl: prevState.vpsUrl,
  4020. vpsPassword: prevState.vpsPassword,
  4021. customPassword: prevState.customPassword,
  4022. autoRunSkipFailures: prevState.autoRunSkipFailures,
  4023. autoRunFallbackThreadIntervalMinutes: prevState.autoRunFallbackThreadIntervalMinutes,
  4024. autoRunDelayEnabled: prevState.autoRunDelayEnabled,
  4025. autoRunDelayMinutes: prevState.autoRunDelayMinutes,
  4026. autoStepDelaySeconds: prevState.autoStepDelaySeconds,
  4027. mailProvider: prevState.mailProvider,
  4028. emailGenerator: prevState.emailGenerator,
  4029. emailPrefix: prevState.emailPrefix,
  4030. inbucketHost: prevState.inbucketHost,
  4031. inbucketMailbox: prevState.inbucketMailbox,
  4032. cloudflareDomain: prevState.cloudflareDomain,
  4033. cloudflareDomains: prevState.cloudflareDomains,
  4034. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  4035. tabRegistry: {},
  4036. sourceLastUrls: {},
  4037. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun }),
  4038. };
  4039. await resetState();
  4040. await setState(keepSettings);
  4041. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => { });
  4042. await sleepWithStop(500);
  4043. } else {
  4044. await setState({
  4045. autoRunSkipFailures,
  4046. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  4047. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun }),
  4048. });
  4049. }
  4050. if (forceFreshTabsNextRun) {
  4051. await addLog(`上一轮尝试已放弃,当前开始第 ${targetRun}/${totalRuns} 轮第 ${attemptRun} 次尝试。`, 'warn');
  4052. forceFreshTabsNextRun = false;
  4053. }
  4054. try {
  4055. throwIfStopped();
  4056. await broadcastAutoRunStatus('running', {
  4057. currentRun: targetRun,
  4058. totalRuns,
  4059. attemptRun,
  4060. });
  4061. await runAutoSequenceFromStep(startStep, {
  4062. targetRun,
  4063. totalRuns,
  4064. attemptRuns: attemptRun,
  4065. continued: useExistingProgress,
  4066. });
  4067. roundSummary.status = 'success';
  4068. roundSummary.finalFailureReason = '';
  4069. successfulRuns += 1;
  4070. await setState({
  4071. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  4072. });
  4073. await addLog(`=== 第 ${targetRun}/${totalRuns} 轮完成(第 ${attemptRun} 次尝试成功)===`, 'ok');
  4074. break;
  4075. } catch (err) {
  4076. if (isStopError(err)) {
  4077. stoppedEarly = true;
  4078. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  4079. await broadcastAutoRunStatus('stopped', {
  4080. currentRun: targetRun,
  4081. totalRuns,
  4082. attemptRun,
  4083. });
  4084. break;
  4085. }
  4086. const reason = getErrorMessage(err);
  4087. roundSummary.failureReasons.push(reason);
  4088. const canRetry = autoRunSkipFailures && attemptRun < maxAttemptsForRound;
  4089. await setState({
  4090. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  4091. });
  4092. if (canRetry) {
  4093. const retryIndex = attemptRun;
  4094. if (isRestartCurrentAttemptError(err)) {
  4095. await addLog(`第 ${targetRun}/${totalRuns} 轮第 ${attemptRun} 次尝试需要整轮重开:${reason}`, 'warn');
  4096. } else {
  4097. await addLog(`第 ${targetRun}/${totalRuns} 轮第 ${attemptRun} 次尝试失败:${reason}`, 'error');
  4098. }
  4099. cancelPendingCommands('当前尝试已放弃。');
  4100. await broadcastStopToContentScripts();
  4101. await broadcastAutoRunStatus('retrying', {
  4102. currentRun: targetRun,
  4103. totalRuns,
  4104. attemptRun,
  4105. });
  4106. forceFreshTabsNextRun = true;
  4107. await addLog(
  4108. `自动重试:${Math.round(AUTO_RUN_RETRY_DELAY_MS / 1000)} 秒后开始第 ${targetRun}/${totalRuns} 轮第 ${attemptRun + 1} 次尝试(第 ${retryIndex}/${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试)。`,
  4109. 'warn'
  4110. );
  4111. try {
  4112. await sleepWithStop(AUTO_RUN_RETRY_DELAY_MS);
  4113. } catch (sleepError) {
  4114. if (isStopError(sleepError)) {
  4115. stoppedEarly = true;
  4116. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  4117. await broadcastAutoRunStatus('stopped', {
  4118. currentRun: targetRun,
  4119. totalRuns,
  4120. attemptRun,
  4121. });
  4122. break;
  4123. }
  4124. throw sleepError;
  4125. }
  4126. try {
  4127. await waitBeforeAutoRunRetry(targetRun, totalRuns, attemptRun + 1);
  4128. } catch (sleepError) {
  4129. if (isStopError(sleepError)) {
  4130. stoppedEarly = true;
  4131. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  4132. await broadcastAutoRunStatus('stopped', {
  4133. currentRun: targetRun,
  4134. totalRuns,
  4135. attemptRun,
  4136. });
  4137. break;
  4138. }
  4139. throw sleepError;
  4140. }
  4141. attemptRun += 1;
  4142. reuseExistingProgress = false;
  4143. continue;
  4144. }
  4145. roundSummary.status = 'failed';
  4146. roundSummary.finalFailureReason = reason;
  4147. await setState({
  4148. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  4149. });
  4150. if (!autoRunSkipFailures) {
  4151. cancelPendingCommands('当前轮执行失败。');
  4152. await broadcastStopToContentScripts();
  4153. await addLog('自动重试未开启,自动运行将在当前失败后停止。', 'warn');
  4154. stoppedEarly = true;
  4155. await broadcastAutoRunStatus('stopped', {
  4156. currentRun: targetRun,
  4157. totalRuns,
  4158. attemptRun,
  4159. });
  4160. break;
  4161. }
  4162. await addLog(`第 ${targetRun}/${totalRuns} 轮最终失败:${reason}`, 'error');
  4163. await addLog(
  4164. targetRun < totalRuns
  4165. ? `第 ${targetRun}/${totalRuns} 轮已达到 ${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试上限,继续下一轮。`
  4166. : `第 ${targetRun}/${totalRuns} 轮已达到 ${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试上限,本次自动运行结束。`,
  4167. 'warn'
  4168. );
  4169. cancelPendingCommands('当前轮已达到重试上限。');
  4170. await broadcastStopToContentScripts();
  4171. forceFreshTabsNextRun = true;
  4172. break;
  4173. } finally {
  4174. reuseExistingProgress = false;
  4175. continueCurrentOnFirstAttempt = false;
  4176. }
  4177. }
  4178. if (stoppedEarly) {
  4179. break;
  4180. }
  4181. try {
  4182. await waitBetweenAutoRunRounds(targetRun, totalRuns, roundSummary);
  4183. } catch (sleepError) {
  4184. if (isStopError(sleepError)) {
  4185. stoppedEarly = true;
  4186. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  4187. await broadcastAutoRunStatus('stopped', {
  4188. currentRun: targetRun,
  4189. totalRuns,
  4190. attemptRun: autoRunAttemptRun,
  4191. });
  4192. break;
  4193. }
  4194. throw sleepError;
  4195. }
  4196. }
  4197. await setState({
  4198. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  4199. });
  4200. await logAutoRunFinalSummary(totalRuns, roundSummaries);
  4201. if (stopRequested || stoppedEarly) {
  4202. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮 ===`, 'warn');
  4203. await broadcastAutoRunStatus('stopped', {
  4204. currentRun: autoRunCurrentRun,
  4205. totalRuns: autoRunTotalRuns,
  4206. attemptRun: autoRunAttemptRun,
  4207. });
  4208. } else {
  4209. await addLog(`=== 全部 ${autoRunTotalRuns} 轮已执行完成,成功 ${successfulRuns} 轮 ===`, 'ok');
  4210. await broadcastAutoRunStatus('complete', {
  4211. currentRun: autoRunTotalRuns,
  4212. totalRuns: autoRunTotalRuns,
  4213. attemptRun: autoRunAttemptRun,
  4214. });
  4215. }
  4216. autoRunActive = false;
  4217. await setState({
  4218. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  4219. ...getAutoRunStatusPayload(stopRequested || stoppedEarly ? 'stopped' : 'complete', {
  4220. currentRun: stopRequested || stoppedEarly ? autoRunCurrentRun : autoRunTotalRuns,
  4221. totalRuns: autoRunTotalRuns,
  4222. attemptRun: autoRunAttemptRun,
  4223. }),
  4224. });
  4225. clearStopRequest();
  4226. }
  4227. async function resumeAutoRun() {
  4228. throwIfStopped();
  4229. const state = await getState();
  4230. if (!state.email) {
  4231. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  4232. return false;
  4233. }
  4234. const resumedInMemory = await resumeAutoRunIfWaitingForEmail({ silent: true });
  4235. if (resumedInMemory) {
  4236. return true;
  4237. }
  4238. if (!isAutoRunPausedState(state)) {
  4239. return false;
  4240. }
  4241. if (autoRunActive) {
  4242. return false;
  4243. }
  4244. const totalRuns = state.autoRunTotalRuns || 1;
  4245. const currentRun = state.autoRunCurrentRun || 1;
  4246. const attemptRun = state.autoRunAttemptRun || 1;
  4247. await addLog('检测到自动流程暂停上下文已丢失,正在从当前进度恢复自动运行...', 'warn');
  4248. startAutoRunLoop(totalRuns, {
  4249. autoRunSkipFailures: Boolean(state.autoRunSkipFailures),
  4250. mode: 'continue',
  4251. resumeCurrentRun: currentRun,
  4252. resumeAttemptRun: attemptRun,
  4253. resumeRoundSummaries: state.autoRunRoundSummaries,
  4254. });
  4255. return true;
  4256. }
  4257. // ============================================================
  4258. // Step 1: Get OAuth Link
  4259. // ============================================================
  4260. async function executeStep1(state) {
  4261. if (getPanelMode(state) === 'sub2api') {
  4262. return executeSub2ApiStep1(state);
  4263. }
  4264. return executeCpaStep1(state);
  4265. }
  4266. async function executeCpaStep1(state) {
  4267. if (!state.vpsUrl) {
  4268. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  4269. }
  4270. await addLog('步骤 1:正在打开 CPA 面板...');
  4271. const injectFiles = ['content/activation-utils.js', 'content/utils.js', 'content/vps-panel.js'];
  4272. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  4273. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  4274. const tabId = tab.id;
  4275. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  4276. await addLog('步骤 1:CPA 面板已打开,正在等待页面进入目标地址...');
  4277. const matchedTab = await waitForTabUrlFamily('vps-panel', tabId, state.vpsUrl, {
  4278. timeoutMs: 15000,
  4279. retryDelayMs: 400,
  4280. });
  4281. if (!matchedTab) {
  4282. await addLog('步骤 1:CPA 页面尚未完全进入目标地址,继续尝试连接内容脚本...', 'warn');
  4283. }
  4284. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  4285. inject: injectFiles,
  4286. timeoutMs: 45000,
  4287. retryDelayMs: 900,
  4288. logMessage: '步骤 1:CPA 面板仍在加载,正在重试连接内容脚本...',
  4289. });
  4290. const result = await sendToContentScriptResilient('vps-panel', {
  4291. type: 'EXECUTE_STEP',
  4292. step: 1,
  4293. source: 'background',
  4294. payload: { vpsPassword: state.vpsPassword },
  4295. }, {
  4296. timeoutMs: 30000,
  4297. retryDelayMs: 700,
  4298. logMessage: '步骤 1:CPA 面板通信未就绪,正在等待页面恢复...',
  4299. });
  4300. if (result?.error) {
  4301. throw new Error(result.error);
  4302. }
  4303. }
  4304. async function executeSub2ApiStep1(state) {
  4305. const sub2apiUrl = normalizeSub2ApiUrl(state.sub2apiUrl);
  4306. const groupName = (state.sub2apiGroupName || DEFAULT_SUB2API_GROUP_NAME).trim() || DEFAULT_SUB2API_GROUP_NAME;
  4307. if (!state.sub2apiEmail) {
  4308. throw new Error('尚未配置 SUB2API 登录邮箱,请先在侧边栏填写。');
  4309. }
  4310. if (!state.sub2apiPassword) {
  4311. throw new Error('尚未配置 SUB2API 登录密码,请先在侧边栏填写。');
  4312. }
  4313. await addLog('步骤 1:正在打开 SUB2API 后台...');
  4314. const injectFiles = ['content/utils.js', 'content/sub2api-panel.js'];
  4315. await closeConflictingTabsForSource('sub2api-panel', sub2apiUrl);
  4316. const tab = await chrome.tabs.create({ url: sub2apiUrl, active: true });
  4317. const tabId = tab.id;
  4318. await rememberSourceLastUrl('sub2api-panel', sub2apiUrl);
  4319. await addLog('步骤 1:SUB2API 页面已打开,正在等待页面进入目标地址...');
  4320. const matchedTab = await waitForTabUrlFamily('sub2api-panel', tabId, sub2apiUrl, {
  4321. timeoutMs: 15000,
  4322. retryDelayMs: 400,
  4323. });
  4324. if (!matchedTab) {
  4325. await addLog('步骤 1:SUB2API 页面尚未稳定,继续尝试连接内容脚本...', 'warn');
  4326. }
  4327. await ensureContentScriptReadyOnTab('sub2api-panel', tabId, {
  4328. inject: injectFiles,
  4329. injectSource: 'sub2api-panel',
  4330. timeoutMs: 45000,
  4331. retryDelayMs: 900,
  4332. logMessage: '步骤 1:SUB2API 页面仍在加载,正在重试连接内容脚本...',
  4333. });
  4334. const result = await sendToContentScript('sub2api-panel', {
  4335. type: 'EXECUTE_STEP',
  4336. step: 1,
  4337. source: 'background',
  4338. payload: {
  4339. sub2apiUrl,
  4340. sub2apiEmail: state.sub2apiEmail,
  4341. sub2apiPassword: state.sub2apiPassword,
  4342. sub2apiGroupName: groupName,
  4343. },
  4344. }, {
  4345. responseTimeoutMs: SUB2API_STEP1_RESPONSE_TIMEOUT_MS,
  4346. });
  4347. if (result?.error) {
  4348. throw new Error(result.error);
  4349. }
  4350. }
  4351. // ============================================================
  4352. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  4353. // ============================================================
  4354. async function executeStep2(state) {
  4355. if (!state.oauthUrl) {
  4356. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  4357. }
  4358. await addLog('步骤 2:正在打开认证链接...');
  4359. await reuseOrCreateTab('signup-page', state.oauthUrl);
  4360. await sendToContentScript('signup-page', {
  4361. type: 'EXECUTE_STEP',
  4362. step: 2,
  4363. source: 'background',
  4364. payload: {},
  4365. });
  4366. }
  4367. // ============================================================
  4368. // Step 3: Fill Email & Password (via signup-page.js)
  4369. // ============================================================
  4370. async function executeStep3(state) {
  4371. let resolvedEmail = state.email;
  4372. if (isHotmailProvider(state)) {
  4373. const account = await ensureHotmailAccountForFlow({
  4374. allowAllocate: true,
  4375. markUsed: true,
  4376. preferredAccountId: state.currentHotmailAccountId || null,
  4377. });
  4378. resolvedEmail = account.email;
  4379. } else if (isGeneratedAliasProvider(state.mailProvider)) {
  4380. resolvedEmail = buildGeneratedAliasEmail(state);
  4381. }
  4382. if (!resolvedEmail) {
  4383. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  4384. }
  4385. const password = state.customPassword || generatePassword();
  4386. if (resolvedEmail !== state.email) {
  4387. await setEmailState(resolvedEmail);
  4388. }
  4389. await setPasswordState(password);
  4390. // Save account record
  4391. const accounts = state.accounts || [];
  4392. accounts.push({ email: resolvedEmail, password, createdAt: new Date().toISOString() });
  4393. await setState({ accounts });
  4394. await addLog(
  4395. `步骤 3:正在填写邮箱 ${resolvedEmail},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  4396. );
  4397. await sendToContentScript('signup-page', {
  4398. type: 'EXECUTE_STEP',
  4399. step: 3,
  4400. source: 'background',
  4401. payload: { email: resolvedEmail, password },
  4402. });
  4403. }
  4404. // ============================================================
  4405. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  4406. // ============================================================
  4407. function getMailConfig(state) {
  4408. const provider = state.mailProvider || 'qq';
  4409. if (provider === 'custom') {
  4410. return { provider: 'custom', label: '自定义邮箱' };
  4411. }
  4412. if (provider === HOTMAIL_PROVIDER) {
  4413. return { provider: HOTMAIL_PROVIDER, label: 'Hotmail(远程/本地)' };
  4414. }
  4415. if (provider === CLOUDFLARE_TEMP_EMAIL_PROVIDER) {
  4416. return { provider: CLOUDFLARE_TEMP_EMAIL_PROVIDER, label: 'Cloudflare Temp Email' };
  4417. }
  4418. if (provider === '163') {
  4419. 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 邮箱' };
  4420. }
  4421. if (provider === '163-vip') {
  4422. 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 邮箱' };
  4423. }
  4424. if (provider === 'inbucket') {
  4425. const host = normalizeInbucketOrigin(state.inbucketHost);
  4426. const mailbox = (state.inbucketMailbox || '').trim();
  4427. if (!host) {
  4428. return { error: 'Inbucket 主机地址为空或无效。' };
  4429. }
  4430. if (!mailbox) {
  4431. return { error: 'Inbucket 邮箱名称为空。' };
  4432. }
  4433. return {
  4434. source: 'inbucket-mail',
  4435. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  4436. label: `Inbucket 邮箱(${mailbox})`,
  4437. navigateOnReuse: true,
  4438. inject: ['content/activation-utils.js', 'content/utils.js', 'content/inbucket-mail.js'],
  4439. injectSource: 'inbucket-mail',
  4440. };
  4441. }
  4442. if (provider === '2925') {
  4443. return {
  4444. source: 'mail-2925',
  4445. url: 'https://2925.com/#/mailList',
  4446. label: '2925 邮箱',
  4447. inject: ['content/utils.js', 'content/mail-2925.js'],
  4448. injectSource: 'mail-2925',
  4449. };
  4450. }
  4451. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  4452. }
  4453. function normalizeInbucketOrigin(rawValue) {
  4454. const value = (rawValue || '').trim();
  4455. if (!value) return '';
  4456. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  4457. try {
  4458. const parsed = new URL(candidate);
  4459. return parsed.origin;
  4460. } catch {
  4461. return '';
  4462. }
  4463. }
  4464. function getVerificationCodeStateKey(step) {
  4465. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  4466. }
  4467. function getVerificationCodeLabel(step) {
  4468. return step === 4 ? '注册' : '登录';
  4469. }
  4470. async function confirmCustomVerificationStepBypass(step) {
  4471. const verificationLabel = getVerificationCodeLabel(step);
  4472. await addLog(`步骤 ${step}:当前为自定义邮箱模式,请手动在页面中输入${verificationLabel}验证码并进入下一页面。`, 'warn');
  4473. let response = null;
  4474. try {
  4475. response = await chrome.runtime.sendMessage({
  4476. type: 'REQUEST_CUSTOM_VERIFICATION_BYPASS_CONFIRMATION',
  4477. payload: { step },
  4478. });
  4479. } catch {
  4480. throw new Error(`步骤 ${step}:无法打开确认弹窗,请先保持侧边栏打开后重试。`);
  4481. }
  4482. if (response?.error) {
  4483. throw new Error(response.error);
  4484. }
  4485. if (!response?.confirmed) {
  4486. throw new Error(`步骤 ${step}:已取消手动${verificationLabel}验证码确认。`);
  4487. }
  4488. await setState({
  4489. lastEmailTimestamp: null,
  4490. signupVerificationRequestedAt: null,
  4491. loginVerificationRequestedAt: null,
  4492. });
  4493. await setStepStatus(step, 'skipped');
  4494. await addLog(`步骤 ${step}:已确认手动完成${verificationLabel}验证码输入,当前步骤已跳过。`, 'warn');
  4495. }
  4496. function getVerificationPollPayload(step, state, overrides = {}) {
  4497. if (step === 4) {
  4498. return {
  4499. filterAfterTimestamp: getHotmailVerificationRequestTimestamp(4, state),
  4500. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  4501. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  4502. targetEmail: state.email,
  4503. maxAttempts: 5,
  4504. intervalMs: 3000,
  4505. ...overrides,
  4506. };
  4507. }
  4508. return {
  4509. filterAfterTimestamp: getHotmailVerificationRequestTimestamp(7, state),
  4510. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  4511. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  4512. targetEmail: state.email,
  4513. maxAttempts: 5,
  4514. intervalMs: 3000,
  4515. ...overrides,
  4516. };
  4517. }
  4518. async function requestVerificationCodeResend(step) {
  4519. throwIfStopped();
  4520. const signupTabId = await getTabId('signup-page');
  4521. if (!signupTabId) {
  4522. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  4523. }
  4524. throwIfStopped();
  4525. await chrome.tabs.update(signupTabId, { active: true });
  4526. throwIfStopped();
  4527. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  4528. throwIfStopped();
  4529. const result = await sendToContentScript('signup-page', {
  4530. type: 'RESEND_VERIFICATION_CODE',
  4531. step,
  4532. source: 'background',
  4533. payload: {},
  4534. });
  4535. if (step === 7) {
  4536. const restartError = getStep7RestartFromStep6Error(result);
  4537. if (restartError) {
  4538. throw restartError;
  4539. }
  4540. }
  4541. if (result && result.error) {
  4542. throw new Error(result.error);
  4543. }
  4544. const currentState = await getState();
  4545. if (currentState.mailProvider === '2925') {
  4546. const mailTabId = await getTabId('mail-2925');
  4547. if (mailTabId) {
  4548. await chrome.tabs.update(mailTabId, { active: true });
  4549. await addLog(`步骤 ${step}:已切换到 2925 邮箱标签页等待新邮件。`, 'info');
  4550. }
  4551. }
  4552. return Date.now();
  4553. }
  4554. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  4555. if (mail.provider === HOTMAIL_PROVIDER) {
  4556. const hotmailPollConfig = getHotmailVerificationPollConfig(step);
  4557. return pollHotmailVerificationCode(step, state, {
  4558. ...getVerificationPollPayload(step, state),
  4559. ...hotmailPollConfig,
  4560. ...pollOverrides,
  4561. });
  4562. }
  4563. if (mail.provider === CLOUDFLARE_TEMP_EMAIL_PROVIDER) {
  4564. return pollCloudflareTempEmailVerificationCode(step, state, {
  4565. ...getVerificationPollPayload(step, state),
  4566. ...pollOverrides,
  4567. });
  4568. }
  4569. if (Number(pollOverrides.resendIntervalMs) > 0) {
  4570. return pollFreshVerificationCodeWithResendInterval(step, state, mail, pollOverrides);
  4571. }
  4572. const stateKey = getVerificationCodeStateKey(step);
  4573. const rejectedCodes = new Set();
  4574. if (state[stateKey]) {
  4575. rejectedCodes.add(state[stateKey]);
  4576. }
  4577. for (const code of (pollOverrides.excludeCodes || [])) {
  4578. if (code) rejectedCodes.add(code);
  4579. }
  4580. let lastError = null;
  4581. const filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  4582. const maxRounds = pollOverrides.maxRounds || VERIFICATION_POLL_MAX_ROUNDS;
  4583. for (let round = 1; round <= maxRounds; round++) {
  4584. throwIfStopped();
  4585. if (round > 1) {
  4586. await requestVerificationCodeResend(step);
  4587. }
  4588. const payload = getVerificationPollPayload(step, state, {
  4589. ...pollOverrides,
  4590. filterAfterTimestamp,
  4591. excludeCodes: [...rejectedCodes],
  4592. });
  4593. try {
  4594. const result = await sendToMailContentScriptResilient(
  4595. mail,
  4596. {
  4597. type: 'POLL_EMAIL',
  4598. step,
  4599. source: 'background',
  4600. payload,
  4601. },
  4602. {
  4603. timeoutMs: 45000,
  4604. maxRecoveryAttempts: 2,
  4605. }
  4606. );
  4607. if (result && result.error) {
  4608. throw new Error(result.error);
  4609. }
  4610. if (!result || !result.code) {
  4611. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  4612. }
  4613. if (rejectedCodes.has(result.code)) {
  4614. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  4615. }
  4616. return result;
  4617. } catch (err) {
  4618. if (isStopError(err)) {
  4619. throw err;
  4620. }
  4621. lastError = err;
  4622. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  4623. if (round < maxRounds) {
  4624. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  4625. }
  4626. }
  4627. }
  4628. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  4629. }
  4630. async function pollFreshVerificationCodeWithResendInterval(step, state, mail, pollOverrides = {}) {
  4631. const stateKey = getVerificationCodeStateKey(step);
  4632. const rejectedCodes = new Set();
  4633. if (state[stateKey]) {
  4634. rejectedCodes.add(state[stateKey]);
  4635. }
  4636. for (const code of (pollOverrides.excludeCodes || [])) {
  4637. if (code) rejectedCodes.add(code);
  4638. }
  4639. const {
  4640. maxRounds: _ignoredMaxRounds,
  4641. resendIntervalMs: _ignoredResendIntervalMs,
  4642. lastResendAt: _ignoredLastResendAt,
  4643. ...payloadOverrides
  4644. } = pollOverrides;
  4645. let lastError = null;
  4646. const filterAfterTimestamp = payloadOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  4647. const maxRounds = pollOverrides.maxRounds || VERIFICATION_POLL_MAX_ROUNDS;
  4648. const resendIntervalMs = Math.max(0, Number(pollOverrides.resendIntervalMs) || 0);
  4649. let lastResendAt = Number(pollOverrides.lastResendAt) || 0;
  4650. for (let round = 1; round <= maxRounds; round++) {
  4651. throwIfStopped();
  4652. if (round > 1) {
  4653. lastResendAt = await requestVerificationCodeResend(step);
  4654. }
  4655. while (true) {
  4656. throwIfStopped();
  4657. const payload = getVerificationPollPayload(step, state, {
  4658. ...payloadOverrides,
  4659. filterAfterTimestamp,
  4660. excludeCodes: [...rejectedCodes],
  4661. });
  4662. if (lastResendAt > 0) {
  4663. const remainingBeforeResendMs = Math.max(0, resendIntervalMs - (Date.now() - lastResendAt));
  4664. const baseMaxAttempts = Math.max(1, Number(payload.maxAttempts) || 5);
  4665. const intervalMs = Math.max(1, Number(payload.intervalMs) || 3000);
  4666. payload.maxAttempts = Math.max(1, Math.min(baseMaxAttempts, Math.floor(remainingBeforeResendMs / intervalMs) + 1));
  4667. }
  4668. try {
  4669. const result = await sendToMailContentScriptResilient(
  4670. mail,
  4671. {
  4672. type: 'POLL_EMAIL',
  4673. step,
  4674. source: 'background',
  4675. payload,
  4676. },
  4677. {
  4678. timeoutMs: 45000,
  4679. maxRecoveryAttempts: 2,
  4680. }
  4681. );
  4682. if (result && result.error) {
  4683. throw new Error(result.error);
  4684. }
  4685. if (!result || !result.code) {
  4686. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  4687. }
  4688. if (rejectedCodes.has(result.code)) {
  4689. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  4690. }
  4691. return {
  4692. ...result,
  4693. lastResendAt,
  4694. };
  4695. } catch (err) {
  4696. if (isStopError(err)) {
  4697. throw err;
  4698. }
  4699. lastError = err;
  4700. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  4701. }
  4702. const remainingBeforeResendMs = lastResendAt > 0
  4703. ? Math.max(0, resendIntervalMs - (Date.now() - lastResendAt))
  4704. : 0;
  4705. if (remainingBeforeResendMs > 0) {
  4706. await addLog(
  4707. `步骤 ${step}:距离下次重新发送验证码还差 ${Math.ceil(remainingBeforeResendMs / 1000)} 秒,继续刷新邮箱(第 ${round}/${maxRounds} 轮)...`,
  4708. 'info'
  4709. );
  4710. continue;
  4711. }
  4712. if (round < maxRounds) {
  4713. await addLog(`步骤 ${step}:已到 25 秒重发间隔,准备重新发送验证码(第 ${round + 1}/${maxRounds} 轮)...`, 'warn');
  4714. }
  4715. break;
  4716. }
  4717. }
  4718. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  4719. }
  4720. async function submitVerificationCode(step, code) {
  4721. const signupTabId = await getTabId('signup-page');
  4722. if (!signupTabId) {
  4723. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  4724. }
  4725. await chrome.tabs.update(signupTabId, { active: true });
  4726. const result = await sendToContentScript('signup-page', {
  4727. type: 'FILL_CODE',
  4728. step,
  4729. source: 'background',
  4730. payload: { code },
  4731. });
  4732. if (step === 7) {
  4733. const restartError = getStep7RestartFromStep6Error(result);
  4734. if (restartError) {
  4735. throw restartError;
  4736. }
  4737. }
  4738. if (result && result.error) {
  4739. throw new Error(result.error);
  4740. }
  4741. return result || {};
  4742. }
  4743. async function resolveVerificationStep(step, state, mail, options = {}) {
  4744. const stateKey = getVerificationCodeStateKey(step);
  4745. const rejectedCodes = new Set();
  4746. const hotmailPollConfig = mail.provider === HOTMAIL_PROVIDER
  4747. ? getHotmailVerificationPollConfig(step)
  4748. : null;
  4749. const ignorePersistedLastCode = Boolean(hotmailPollConfig?.ignorePersistedLastCode);
  4750. if (state[stateKey] && !ignorePersistedLastCode) {
  4751. rejectedCodes.add(state[stateKey]);
  4752. }
  4753. const nextFilterAfterTimestamp = options.filterAfterTimestamp ?? null;
  4754. const requestFreshCodeFirst = options.requestFreshCodeFirst !== undefined
  4755. ? Boolean(options.requestFreshCodeFirst)
  4756. : (hotmailPollConfig?.requestFreshCodeFirst ?? false);
  4757. const maxSubmitAttempts = 3;
  4758. const resendIntervalMs = Math.max(0, Number(options.resendIntervalMs) || 0);
  4759. let lastResendAt = Number(options.lastResendAt) || 0;
  4760. if (requestFreshCodeFirst) {
  4761. try {
  4762. lastResendAt = await requestVerificationCodeResend(step);
  4763. await addLog(`步骤 ${step}:已先请求一封新的${getVerificationCodeLabel(step)}验证码,再开始轮询邮箱。`, 'warn');
  4764. } catch (err) {
  4765. if (isStopError(err) || (step === 7 && isStep7RestartFromStep6Error(err))) {
  4766. throw err;
  4767. }
  4768. await addLog(`步骤 ${step}:首次重新获取验证码失败:${err.message},将继续使用当前时间窗口轮询。`, 'warn');
  4769. }
  4770. }
  4771. if (mail.provider === HOTMAIL_PROVIDER) {
  4772. const initialDelayMs = Number(options.initialDelayMs ?? hotmailPollConfig.initialDelayMs) || 0;
  4773. if (initialDelayMs > 0) {
  4774. await addLog(`步骤 ${step}:等待 ${Math.round(initialDelayMs / 1000)} 秒,让 Hotmail 验证码邮件先到达...`, 'info');
  4775. await sleepWithStop(initialDelayMs);
  4776. }
  4777. }
  4778. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  4779. const result = await pollFreshVerificationCode(step, state, mail, {
  4780. excludeCodes: [...rejectedCodes],
  4781. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  4782. resendIntervalMs,
  4783. lastResendAt,
  4784. });
  4785. lastResendAt = Number(result?.lastResendAt) || lastResendAt;
  4786. throwIfStopped();
  4787. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  4788. throwIfStopped();
  4789. const submitResult = await submitVerificationCode(step, result.code);
  4790. if (submitResult.invalidCode) {
  4791. rejectedCodes.add(result.code);
  4792. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  4793. if (attempt >= maxSubmitAttempts) {
  4794. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  4795. }
  4796. const remainingBeforeResendMs = resendIntervalMs > 0 && lastResendAt > 0
  4797. ? Math.max(0, resendIntervalMs - (Date.now() - lastResendAt))
  4798. : 0;
  4799. if (remainingBeforeResendMs > 0) {
  4800. await addLog(
  4801. `步骤 ${step}:提交失败后距离下次重新发送验证码还差 ${Math.ceil(remainingBeforeResendMs / 1000)} 秒,先继续刷新邮箱(${attempt + 1}/${maxSubmitAttempts})...`,
  4802. 'warn'
  4803. );
  4804. continue;
  4805. }
  4806. lastResendAt = await requestVerificationCodeResend(step);
  4807. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  4808. continue;
  4809. }
  4810. await setState({
  4811. lastEmailTimestamp: result.emailTimestamp,
  4812. [stateKey]: result.code,
  4813. });
  4814. await completeStepFromBackground(step, {
  4815. emailTimestamp: result.emailTimestamp,
  4816. code: result.code,
  4817. });
  4818. return;
  4819. }
  4820. }
  4821. async function executeStep4(state) {
  4822. const mail = getMailConfig(state);
  4823. if (mail.error) throw new Error(mail.error);
  4824. const stepStartedAt = Date.now();
  4825. const signupTabId = await getTabId('signup-page');
  4826. if (!signupTabId) {
  4827. throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
  4828. }
  4829. await chrome.tabs.update(signupTabId, { active: true });
  4830. throwIfStopped();
  4831. await addLog('步骤 4:正在确认注册验证码页面是否就绪,必要时自动恢复密码页超时报错...');
  4832. const prepareResult = await sendToContentScriptResilient(
  4833. 'signup-page',
  4834. {
  4835. type: 'PREPARE_SIGNUP_VERIFICATION',
  4836. step: 4,
  4837. source: 'background',
  4838. payload: { password: state.password || state.customPassword || '' },
  4839. },
  4840. {
  4841. timeoutMs: 30000,
  4842. retryDelayMs: 700,
  4843. logMessage: '步骤 4:认证页正在切换,等待页面重新就绪后继续检测...',
  4844. }
  4845. );
  4846. if (prepareResult && prepareResult.error) {
  4847. throw new Error(prepareResult.error);
  4848. }
  4849. if (prepareResult?.verificationRequestedAt) {
  4850. await setState({ loginVerificationRequestedAt: prepareResult.verificationRequestedAt });
  4851. }
  4852. if (prepareResult?.alreadyVerified) {
  4853. await completeStepFromBackground(4, {});
  4854. return;
  4855. }
  4856. if (shouldUseCustomRegistrationEmail(state)) {
  4857. await confirmCustomVerificationStepBypass(4);
  4858. return;
  4859. }
  4860. throwIfStopped();
  4861. if (mail.provider === HOTMAIL_PROVIDER || mail.provider === CLOUDFLARE_TEMP_EMAIL_PROVIDER) {
  4862. await addLog(`步骤 4:正在通过 ${mail.label} 轮询验证码...`);
  4863. } else {
  4864. await addLog(`步骤 4:正在打开${mail.label}...`);
  4865. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  4866. const alive = await isTabAlive(mail.source);
  4867. if (alive) {
  4868. if (mail.navigateOnReuse) {
  4869. await reuseOrCreateTab(mail.source, mail.url, {
  4870. inject: mail.inject,
  4871. injectSource: mail.injectSource,
  4872. });
  4873. } else {
  4874. const tabId = await getTabId(mail.source);
  4875. await chrome.tabs.update(tabId, { active: true });
  4876. }
  4877. } else {
  4878. await reuseOrCreateTab(mail.source, mail.url, {
  4879. inject: mail.inject,
  4880. injectSource: mail.injectSource,
  4881. });
  4882. }
  4883. }
  4884. await resolveVerificationStep(4, state, mail, {
  4885. filterAfterTimestamp: mail.provider === HOTMAIL_PROVIDER ? undefined : stepStartedAt,
  4886. requestFreshCodeFirst: mail.provider === HOTMAIL_PROVIDER ? false : true,
  4887. resendIntervalMs: mail.provider === HOTMAIL_PROVIDER ? 0 : STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS,
  4888. });
  4889. return;
  4890. }
  4891. // ============================================================
  4892. // Step 5: Fill Name & Birthday (via signup-page.js)
  4893. // ============================================================
  4894. async function executeStep5(state) {
  4895. const { firstName, lastName } = generateRandomName();
  4896. const { year, month, day } = generateRandomBirthday();
  4897. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  4898. await sendToContentScript('signup-page', {
  4899. type: 'EXECUTE_STEP',
  4900. step: 5,
  4901. source: 'background',
  4902. payload: { firstName, lastName, year, month, day },
  4903. });
  4904. }
  4905. // ============================================================
  4906. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  4907. // ============================================================
  4908. async function refreshOAuthUrlBeforeStep6(state) {
  4909. await addLog(`步骤 6:正在刷新登录用的 ${getPanelModeLabel(state)} OAuth 链接...`);
  4910. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] preparing fresh OAuth via step 1');
  4911. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  4912. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] executing step 1 for fresh OAuth');
  4913. await executeStep1(state);
  4914. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 execute returned, waiting for completion signal');
  4915. await waitForFreshOAuth;
  4916. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 completion signal received');
  4917. const latestState = await getState();
  4918. if (!latestState.oauthUrl) {
  4919. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  4920. }
  4921. return latestState.oauthUrl;
  4922. }
  4923. async function executeStep6(state) {
  4924. if (!state.email) {
  4925. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  4926. }
  4927. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  4928. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  4929. // Reuse the signup-page tab — navigate it to the OAuth URL
  4930. await reuseOrCreateTab('signup-page', oauthUrl);
  4931. // signup-page.js will inject (same auth.openai.com domain) and handle login
  4932. await sendToContentScript('signup-page', {
  4933. type: 'EXECUTE_STEP',
  4934. step: 6,
  4935. source: 'background',
  4936. payload: { email: state.email, password: state.password },
  4937. });
  4938. }
  4939. // ============================================================
  4940. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  4941. // ============================================================
  4942. async function runStep7Attempt(state) {
  4943. const mail = getMailConfig(state);
  4944. if (mail.error) throw new Error(mail.error);
  4945. const stepStartedAt = Date.now();
  4946. const authTabId = await getTabId('signup-page');
  4947. if (authTabId) {
  4948. await chrome.tabs.update(authTabId, { active: true });
  4949. } else {
  4950. if (!state.oauthUrl) {
  4951. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  4952. }
  4953. await reuseOrCreateTab('signup-page', state.oauthUrl);
  4954. }
  4955. throwIfStopped();
  4956. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  4957. const prepareResult = await sendToContentScript('signup-page', {
  4958. type: 'PREPARE_LOGIN_CODE',
  4959. step: 7,
  4960. source: 'background',
  4961. payload: {},
  4962. });
  4963. const restartError = getStep7RestartFromStep6Error(prepareResult);
  4964. if (restartError) {
  4965. throw restartError;
  4966. }
  4967. if (prepareResult && prepareResult.error) {
  4968. throw new Error(prepareResult.error);
  4969. }
  4970. if (shouldUseCustomRegistrationEmail(state)) {
  4971. await confirmCustomVerificationStepBypass(7);
  4972. return;
  4973. }
  4974. throwIfStopped();
  4975. if (mail.provider === HOTMAIL_PROVIDER || mail.provider === CLOUDFLARE_TEMP_EMAIL_PROVIDER) {
  4976. await addLog(`步骤 7:正在通过 ${mail.label} 轮询验证码...`);
  4977. } else {
  4978. await addLog(`步骤 7:正在打开${mail.label}...`);
  4979. const alive = await isTabAlive(mail.source);
  4980. if (alive) {
  4981. if (mail.navigateOnReuse) {
  4982. await reuseOrCreateTab(mail.source, mail.url, {
  4983. inject: mail.inject,
  4984. injectSource: mail.injectSource,
  4985. });
  4986. } else {
  4987. const tabId = await getTabId(mail.source);
  4988. await chrome.tabs.update(tabId, { active: true });
  4989. }
  4990. } else {
  4991. await reuseOrCreateTab(mail.source, mail.url, {
  4992. inject: mail.inject,
  4993. injectSource: mail.injectSource,
  4994. });
  4995. }
  4996. }
  4997. await resolveVerificationStep(7, state, mail, {
  4998. filterAfterTimestamp: mail.provider === HOTMAIL_PROVIDER ? undefined : stepStartedAt,
  4999. requestFreshCodeFirst: mail.provider === HOTMAIL_PROVIDER ? false : true,
  5000. resendIntervalMs: mail.provider === HOTMAIL_PROVIDER ? 0 : STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS,
  5001. });
  5002. }
  5003. async function rerunStep6ForStep7Recovery() {
  5004. const currentState = await getState();
  5005. const waitForStep6 = waitForStepComplete(6, 120000);
  5006. await addLog('步骤 7:正在回到步骤 6,重新发起登录验证码流程...', 'warn');
  5007. await executeStep6(currentState);
  5008. await waitForStep6;
  5009. await sleepWithStop(3000);
  5010. }
  5011. async function executeStep7(state) {
  5012. let currentState = state;
  5013. let mailPollingAttempt = 1;
  5014. let lastMailPollingError = null;
  5015. while (true) {
  5016. try {
  5017. await runStep7Attempt(currentState);
  5018. return;
  5019. } catch (err) {
  5020. if (isStep7RestartFromStep6Error(err)) {
  5021. await addLog('步骤 7:检测到登录页超时报错,准备从步骤 6 重新开始...', 'warn');
  5022. await rerunStep6ForStep7Recovery();
  5023. currentState = await getState();
  5024. continue;
  5025. }
  5026. if (!isVerificationMailPollingError(err)) {
  5027. throw err;
  5028. }
  5029. lastMailPollingError = err;
  5030. if (mailPollingAttempt >= STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS) {
  5031. break;
  5032. }
  5033. mailPollingAttempt += 1;
  5034. await addLog(
  5035. `步骤 7:检测到邮箱轮询类失败,准备从步骤 6 重新开始(${mailPollingAttempt}/${STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS})...`,
  5036. 'warn'
  5037. );
  5038. await rerunStep6ForStep7Recovery();
  5039. currentState = await getState();
  5040. }
  5041. }
  5042. if (lastMailPollingError) {
  5043. throw new Error(
  5044. `步骤 7:登录验证码流程在 ${STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS} 轮邮箱轮询恢复后仍未成功。最后一次原因:${lastMailPollingError.message}`
  5045. );
  5046. }
  5047. throw new Error('步骤 7:登录验证码流程未成功完成。');
  5048. }
  5049. // ============================================================
  5050. // Step 8: 完成 OAuth(自动点击 + localhost 回调监听)
  5051. // ============================================================
  5052. let webNavListener = null;
  5053. let webNavCommittedListener = null;
  5054. let step8TabUpdatedListener = null;
  5055. let step8PendingReject = null;
  5056. const STEP8_CLICK_EFFECT_TIMEOUT_MS = 15000;
  5057. const STEP8_CLICK_RETRY_DELAY_MS = 500;
  5058. const STEP8_READY_WAIT_TIMEOUT_MS = 30000;
  5059. const STEP8_MAX_ROUNDS = 5;
  5060. const STEP8_SIGNUP_PAGE_INJECT_FILES = ['content/utils.js', 'content/signup-page.js'];
  5061. const STEP8_STRATEGIES = [
  5062. { mode: 'content', strategy: 'requestSubmit', label: 'form.requestSubmit' },
  5063. { mode: 'debugger', label: 'debugger click' },
  5064. { mode: 'content', strategy: 'nativeClick', label: 'element.click' },
  5065. { mode: 'content', strategy: 'dispatchClick', label: 'dispatch click' },
  5066. { mode: 'debugger', label: 'debugger click retry' },
  5067. ];
  5068. function cleanupStep8NavigationListeners() {
  5069. if (webNavListener) {
  5070. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  5071. webNavListener = null;
  5072. }
  5073. if (webNavCommittedListener) {
  5074. chrome.webNavigation.onCommitted.removeListener(webNavCommittedListener);
  5075. webNavCommittedListener = null;
  5076. }
  5077. if (step8TabUpdatedListener) {
  5078. chrome.tabs.onUpdated.removeListener(step8TabUpdatedListener);
  5079. step8TabUpdatedListener = null;
  5080. }
  5081. }
  5082. function rejectPendingStep8(error) {
  5083. if (!step8PendingReject) return;
  5084. const reject = step8PendingReject;
  5085. step8PendingReject = null;
  5086. reject(error);
  5087. }
  5088. function throwIfStep8SettledOrStopped(isSettled = false) {
  5089. if (isSettled || stopRequested) {
  5090. throw new Error(STOP_ERROR_MESSAGE);
  5091. }
  5092. }
  5093. async function ensureStep8SignupPageReady(tabId, options = {}) {
  5094. await ensureContentScriptReadyOnTab('signup-page', tabId, {
  5095. inject: STEP8_SIGNUP_PAGE_INJECT_FILES,
  5096. injectSource: 'signup-page',
  5097. timeoutMs: options.timeoutMs ?? 15000,
  5098. retryDelayMs: options.retryDelayMs ?? 600,
  5099. logMessage: options.logMessage || '',
  5100. });
  5101. }
  5102. async function getStep8PageState(tabId, responseTimeoutMs = 1500) {
  5103. try {
  5104. const result = await sendTabMessageWithTimeout(tabId, 'signup-page', {
  5105. type: 'STEP8_GET_STATE',
  5106. source: 'background',
  5107. payload: {},
  5108. }, responseTimeoutMs);
  5109. if (result?.error) {
  5110. throw new Error(result.error);
  5111. }
  5112. return result;
  5113. } catch (err) {
  5114. if (isRetryableContentScriptTransportError(err)) {
  5115. return null;
  5116. }
  5117. throw err;
  5118. }
  5119. }
  5120. async function waitForStep8Ready(tabId, timeoutMs = STEP8_READY_WAIT_TIMEOUT_MS) {
  5121. const start = Date.now();
  5122. let recovered = false;
  5123. while (Date.now() - start < timeoutMs) {
  5124. throwIfStopped();
  5125. const pageState = await getStep8PageState(tabId);
  5126. if (pageState?.addPhonePage) {
  5127. throw new Error('步骤 8:认证页进入了手机号页面,当前不是 OAuth 同意页,无法继续自动授权。');
  5128. }
  5129. if (pageState?.consentReady) {
  5130. return pageState;
  5131. }
  5132. if (pageState === null && !recovered) {
  5133. recovered = true;
  5134. await ensureStep8SignupPageReady(tabId, {
  5135. timeoutMs: Math.min(10000, timeoutMs),
  5136. logMessage: '步骤 8:认证页内容脚本已失联,正在等待页面重新就绪...',
  5137. });
  5138. continue;
  5139. }
  5140. recovered = false;
  5141. await sleepWithStop(250);
  5142. }
  5143. throw new Error('步骤 8:长时间未进入 OAuth 同意页,无法定位“继续”按钮。');
  5144. }
  5145. async function prepareStep8DebuggerClick(tabId) {
  5146. await ensureStep8SignupPageReady(tabId, {
  5147. timeoutMs: 15000,
  5148. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续定位按钮...',
  5149. });
  5150. const result = await sendToContentScriptResilient('signup-page', {
  5151. type: 'STEP8_FIND_AND_CLICK',
  5152. source: 'background',
  5153. payload: {},
  5154. }, {
  5155. timeoutMs: 15000,
  5156. retryDelayMs: 600,
  5157. logMessage: '步骤 8:认证页正在切换,等待 OAuth 同意页按钮重新就绪...',
  5158. });
  5159. if (result?.error) {
  5160. throw new Error(result.error);
  5161. }
  5162. return result;
  5163. }
  5164. async function triggerStep8ContentStrategy(tabId, strategy) {
  5165. await ensureStep8SignupPageReady(tabId, {
  5166. timeoutMs: 15000,
  5167. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续点击“继续”按钮...',
  5168. });
  5169. const result = await sendToContentScriptResilient('signup-page', {
  5170. type: 'STEP8_TRIGGER_CONTINUE',
  5171. source: 'background',
  5172. payload: {
  5173. strategy,
  5174. findTimeoutMs: 4000,
  5175. enabledTimeoutMs: 3000,
  5176. },
  5177. }, {
  5178. timeoutMs: 15000,
  5179. retryDelayMs: 600,
  5180. logMessage: '步骤 8:认证页正在切换,等待“继续”按钮重新就绪...',
  5181. });
  5182. if (result?.error) {
  5183. throw new Error(result.error);
  5184. }
  5185. return result;
  5186. }
  5187. async function reloadStep8ConsentPage(tabId, timeoutMs = 30000) {
  5188. if (!Number.isInteger(tabId)) {
  5189. throw new Error('步骤 8:缺少有效的认证页标签页,无法刷新后重试。');
  5190. }
  5191. await chrome.tabs.update(tabId, { active: true }).catch(() => { });
  5192. await new Promise((resolve, reject) => {
  5193. let settled = false;
  5194. const timer = setTimeout(() => {
  5195. if (settled) return;
  5196. settled = true;
  5197. chrome.tabs.onUpdated.removeListener(listener);
  5198. reject(new Error('步骤 8:刷新认证页后等待页面完成加载超时。'));
  5199. }, timeoutMs);
  5200. const listener = (updatedTabId, changeInfo) => {
  5201. if (updatedTabId !== tabId) return;
  5202. if (changeInfo.status !== 'complete') return;
  5203. if (settled) return;
  5204. settled = true;
  5205. clearTimeout(timer);
  5206. chrome.tabs.onUpdated.removeListener(listener);
  5207. resolve();
  5208. };
  5209. chrome.tabs.onUpdated.addListener(listener);
  5210. chrome.tabs.reload(tabId, { bypassCache: false }).catch((err) => {
  5211. if (settled) return;
  5212. settled = true;
  5213. clearTimeout(timer);
  5214. chrome.tabs.onUpdated.removeListener(listener);
  5215. reject(err);
  5216. });
  5217. });
  5218. await ensureStep8SignupPageReady(tabId, {
  5219. timeoutMs: Math.min(15000, timeoutMs),
  5220. logMessage: '步骤 8:认证页刷新后内容脚本尚未就绪,正在等待页面恢复...',
  5221. });
  5222. }
  5223. async function waitForStep8ClickEffect(tabId, baselineUrl, timeoutMs = STEP8_CLICK_EFFECT_TIMEOUT_MS) {
  5224. const start = Date.now();
  5225. let recovered = false;
  5226. while (Date.now() - start < timeoutMs) {
  5227. throwIfStopped();
  5228. const tab = await chrome.tabs.get(tabId).catch(() => null);
  5229. if (!tab) {
  5230. throw new Error('步骤 8:认证页面标签页已关闭,无法继续自动授权。');
  5231. }
  5232. if (baselineUrl && typeof tab.url === 'string' && tab.url !== baselineUrl) {
  5233. return { progressed: true, reason: 'url_changed', url: tab.url };
  5234. }
  5235. const pageState = await getStep8PageState(tabId);
  5236. if (pageState?.addPhonePage) {
  5237. throw new Error('步骤 8:点击“继续”后页面跳到了手机号页面,当前流程无法继续自动授权。');
  5238. }
  5239. if (pageState === null) {
  5240. if (!recovered) {
  5241. recovered = true;
  5242. await ensureStep8SignupPageReady(tabId, {
  5243. timeoutMs: Math.max(3000, Math.min(8000, timeoutMs)),
  5244. logMessage: '步骤 8:点击后认证页正在重载,正在等待内容脚本重新就绪...',
  5245. }).catch(() => null);
  5246. continue;
  5247. }
  5248. await sleepWithStop(200);
  5249. continue;
  5250. }
  5251. recovered = false;
  5252. await sleepWithStop(200);
  5253. }
  5254. return { progressed: false, reason: 'no_effect' };
  5255. }
  5256. function getStep8EffectLabel(effect) {
  5257. switch (effect?.reason) {
  5258. case 'url_changed':
  5259. return `URL 已变化:${effect.url}`;
  5260. case 'page_reloading':
  5261. return '页面正在跳转或重载';
  5262. case 'left_consent_page':
  5263. return `页面已离开 OAuth 同意页:${effect.url || 'unknown'}`;
  5264. default:
  5265. return '页面仍停留在 OAuth 同意页';
  5266. }
  5267. }
  5268. async function executeStep8(state) {
  5269. if (!state.oauthUrl) {
  5270. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  5271. }
  5272. await addLog('步骤 8:正在监听 localhost 回调地址...');
  5273. return new Promise((resolve, reject) => {
  5274. let resolved = false;
  5275. let signupTabId = null;
  5276. const cleanupListener = () => {
  5277. cleanupStep8NavigationListeners();
  5278. step8PendingReject = null;
  5279. };
  5280. const rejectStep8 = (error) => {
  5281. if (resolved) return;
  5282. resolved = true;
  5283. clearTimeout(timeout);
  5284. cleanupListener();
  5285. reject(error);
  5286. };
  5287. const finalizeStep8Callback = (callbackUrl) => {
  5288. if (resolved || !callbackUrl) return;
  5289. resolved = true;
  5290. cleanupListener();
  5291. clearTimeout(timeout);
  5292. addLog(`步骤 8:已捕获 localhost 地址:${callbackUrl}`, 'ok').then(() => {
  5293. return completeStepFromBackground(8, { localhostUrl: callbackUrl });
  5294. }).then(() => {
  5295. resolve();
  5296. }).catch((err) => {
  5297. reject(err);
  5298. });
  5299. };
  5300. const timeout = setTimeout(() => {
  5301. rejectStep8(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  5302. }, 120000);
  5303. step8PendingReject = (error) => {
  5304. rejectStep8(error);
  5305. };
  5306. webNavListener = (details) => {
  5307. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  5308. finalizeStep8Callback(callbackUrl);
  5309. };
  5310. webNavCommittedListener = (details) => {
  5311. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  5312. finalizeStep8Callback(callbackUrl);
  5313. };
  5314. step8TabUpdatedListener = (tabId, changeInfo, tab) => {
  5315. const callbackUrl = getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId);
  5316. finalizeStep8Callback(callbackUrl);
  5317. };
  5318. (async () => {
  5319. try {
  5320. throwIfStep8SettledOrStopped(resolved);
  5321. signupTabId = await getTabId('signup-page');
  5322. throwIfStep8SettledOrStopped(resolved);
  5323. if (signupTabId && await isTabAlive('signup-page')) {
  5324. await chrome.tabs.update(signupTabId, { active: true });
  5325. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  5326. } else {
  5327. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  5328. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  5329. }
  5330. throwIfStep8SettledOrStopped(resolved);
  5331. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  5332. chrome.webNavigation.onCommitted.addListener(webNavCommittedListener);
  5333. chrome.tabs.onUpdated.addListener(step8TabUpdatedListener);
  5334. await ensureStep8SignupPageReady(signupTabId, {
  5335. timeoutMs: 15000,
  5336. logMessage: '步骤 8:认证页内容脚本尚未就绪,正在等待页面恢复...',
  5337. });
  5338. for (let round = 1; round <= STEP8_MAX_ROUNDS && !resolved; round++) {
  5339. throwIfStep8SettledOrStopped(resolved);
  5340. const pageState = await waitForStep8Ready(signupTabId);
  5341. if (!pageState?.consentReady) {
  5342. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  5343. continue;
  5344. }
  5345. const strategy = STEP8_STRATEGIES[Math.min(round - 1, STEP8_STRATEGIES.length - 1)];
  5346. await addLog(`步骤 8:第 ${round}/${STEP8_MAX_ROUNDS} 轮尝试点击“继续”(${strategy.label})...`);
  5347. if (strategy.mode === 'debugger') {
  5348. const clickTarget = await prepareStep8DebuggerClick(signupTabId);
  5349. throwIfStep8SettledOrStopped(resolved);
  5350. await clickWithDebugger(signupTabId, clickTarget?.rect);
  5351. } else {
  5352. await triggerStep8ContentStrategy(signupTabId, strategy.strategy);
  5353. }
  5354. if (resolved) {
  5355. return;
  5356. }
  5357. const effect = await waitForStep8ClickEffect(signupTabId, pageState.url);
  5358. if (resolved) {
  5359. return;
  5360. }
  5361. if (effect.progressed) {
  5362. await addLog(`步骤 8:检测到本次点击已生效,${getStep8EffectLabel(effect)},继续等待 localhost 回调...`, 'info');
  5363. break;
  5364. }
  5365. if (round >= STEP8_MAX_ROUNDS) {
  5366. throw new Error(`步骤 8:连续 ${STEP8_MAX_ROUNDS} 轮点击“继续”后页面仍无反应。`);
  5367. }
  5368. await addLog(`步骤 8:${strategy.label} 本轮点击后页面无反应,正在刷新认证页后重试(下一轮 ${round + 1}/${STEP8_MAX_ROUNDS})...`, 'warn');
  5369. await reloadStep8ConsentPage(signupTabId);
  5370. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  5371. }
  5372. } catch (err) {
  5373. rejectStep8(err);
  5374. }
  5375. })();
  5376. });
  5377. }
  5378. // ============================================================
  5379. // Step 9: 平台回调验证
  5380. // ============================================================
  5381. async function executeStep9(state) {
  5382. if (getPanelMode(state) === 'sub2api') {
  5383. return executeSub2ApiStep9(state);
  5384. }
  5385. return executeCpaStep9(state);
  5386. }
  5387. async function executeCpaStep9(state) {
  5388. if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
  5389. throw new Error('步骤 8 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 8。');
  5390. }
  5391. if (!state.localhostUrl) {
  5392. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  5393. }
  5394. if (!state.vpsUrl) {
  5395. throw new Error('尚未填写 CPA 地址,请先在侧边栏输入。');
  5396. }
  5397. if (shouldBypassStep9ForLocalCpa(state)) {
  5398. await addLog('步骤 9:检测到本地 CPA,且当前策略为“跳过第9步”,本轮不再重复提交回调地址。', 'info');
  5399. await completeStepFromBackground(9, {
  5400. localhostUrl: state.localhostUrl,
  5401. verifiedStatus: 'local-auto',
  5402. });
  5403. return;
  5404. }
  5405. await addLog('步骤 9:正在打开 CPA 面板...');
  5406. const injectFiles = ['content/activation-utils.js', 'content/utils.js', 'content/vps-panel.js'];
  5407. let tabId = await getTabId('vps-panel');
  5408. const alive = tabId && await isTabAlive('vps-panel');
  5409. if (!alive) {
  5410. tabId = await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  5411. inject: injectFiles,
  5412. reloadIfSameUrl: true,
  5413. });
  5414. } else {
  5415. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  5416. await chrome.tabs.update(tabId, { active: true });
  5417. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  5418. }
  5419. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  5420. inject: injectFiles,
  5421. timeoutMs: 45000,
  5422. retryDelayMs: 900,
  5423. logMessage: '姝ラ 9锛欳PA 闈㈡澘浠嶅湪鍔犺浇锛屾鍦ㄩ噸璇曡繛鎺ュ唴瀹硅剼鏈?..',
  5424. });
  5425. await addLog('步骤 9:正在填写回调地址...');
  5426. const result = await sendToContentScriptResilient('vps-panel', {
  5427. type: 'EXECUTE_STEP',
  5428. step: 9,
  5429. source: 'background',
  5430. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  5431. }, {
  5432. timeoutMs: 30000,
  5433. retryDelayMs: 700,
  5434. logMessage: '步骤 9:CPA 面板通信未就绪,正在等待页面恢复...',
  5435. });
  5436. if (result?.error) {
  5437. throw new Error(result.error);
  5438. }
  5439. }
  5440. async function executeSub2ApiStep9(state) {
  5441. if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
  5442. throw new Error('步骤 8 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 8。');
  5443. }
  5444. if (!state.localhostUrl) {
  5445. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  5446. }
  5447. if (!state.sub2apiSessionId) {
  5448. throw new Error('缺少 SUB2API 会话信息,请重新执行步骤 1。');
  5449. }
  5450. if (!state.sub2apiEmail) {
  5451. throw new Error('尚未配置 SUB2API 登录邮箱,请先在侧边栏填写。');
  5452. }
  5453. if (!state.sub2apiPassword) {
  5454. throw new Error('尚未配置 SUB2API 登录密码,请先在侧边栏填写。');
  5455. }
  5456. const sub2apiUrl = normalizeSub2ApiUrl(state.sub2apiUrl);
  5457. const injectFiles = ['content/utils.js', 'content/sub2api-panel.js'];
  5458. await addLog('步骤 9:正在打开 SUB2API 后台...');
  5459. let tabId = await getTabId('sub2api-panel');
  5460. const alive = tabId && await isTabAlive('sub2api-panel');
  5461. if (!alive) {
  5462. tabId = await reuseOrCreateTab('sub2api-panel', sub2apiUrl, {
  5463. inject: injectFiles,
  5464. injectSource: 'sub2api-panel',
  5465. reloadIfSameUrl: true,
  5466. });
  5467. } else {
  5468. await closeConflictingTabsForSource('sub2api-panel', sub2apiUrl, { excludeTabIds: [tabId] });
  5469. await chrome.tabs.update(tabId, { active: true });
  5470. await rememberSourceLastUrl('sub2api-panel', sub2apiUrl);
  5471. }
  5472. await ensureContentScriptReadyOnTab('sub2api-panel', tabId, {
  5473. inject: injectFiles,
  5474. injectSource: 'sub2api-panel',
  5475. });
  5476. await addLog('步骤 9:正在向 SUB2API 提交回调并创建账号...');
  5477. const result = await sendToContentScript('sub2api-panel', {
  5478. type: 'EXECUTE_STEP',
  5479. step: 9,
  5480. source: 'background',
  5481. payload: {
  5482. localhostUrl: state.localhostUrl,
  5483. sub2apiUrl,
  5484. sub2apiEmail: state.sub2apiEmail,
  5485. sub2apiPassword: state.sub2apiPassword,
  5486. sub2apiGroupName: state.sub2apiGroupName,
  5487. sub2apiSessionId: state.sub2apiSessionId,
  5488. sub2apiOAuthState: state.sub2apiOAuthState,
  5489. sub2apiGroupId: state.sub2apiGroupId,
  5490. sub2apiDraftName: state.sub2apiDraftName,
  5491. },
  5492. }, {
  5493. responseTimeoutMs: SUB2API_STEP9_RESPONSE_TIMEOUT_MS,
  5494. });
  5495. if (result?.error) {
  5496. throw new Error(result.error);
  5497. }
  5498. }
  5499. // ============================================================
  5500. // Open Side Panel on extension icon click
  5501. // ============================================================
  5502. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
  5503. chrome.alarms.onAlarm.addListener((alarm) => {
  5504. if (alarm.name !== AUTO_RUN_ALARM_NAME) {
  5505. return;
  5506. }
  5507. launchScheduledAutoRun('alarm').catch((err) => {
  5508. console.error(LOG_PREFIX, 'Failed to launch scheduled auto run from alarm:', err);
  5509. });
  5510. });
  5511. chrome.runtime.onStartup.addListener(() => {
  5512. restoreScheduledAutoRunIfNeeded().catch((err) => {
  5513. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on startup:', err);
  5514. });
  5515. });
  5516. chrome.runtime.onInstalled.addListener(() => {
  5517. restoreScheduledAutoRunIfNeeded().catch((err) => {
  5518. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on install/update:', err);
  5519. });
  5520. });
  5521. restoreScheduledAutoRunIfNeeded().catch((err) => {
  5522. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run:', err);
  5523. });