background.js 266 KB

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