background.js 271 KB

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