background.js 275 KB

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