background.js 281 KB

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