background.js 231 KB

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