background.js 285 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496
  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 = 10000;
  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 isSignupPasswordPageUrl(rawUrl) {
  2863. const parsed = parseUrlSafely(rawUrl);
  2864. if (!parsed) return false;
  2865. return isSignupPageHost(parsed.hostname)
  2866. && /\/create-account\/password(?:[/?#]|$)/i.test(parsed.pathname || '');
  2867. }
  2868. function is163MailHost(hostname = '') {
  2869. return hostname === 'mail.163.com'
  2870. || hostname.endsWith('.mail.163.com')
  2871. || hostname === 'webmail.vip.163.com';
  2872. }
  2873. function isLocalhostOAuthCallbackUrl(rawUrl) {
  2874. const parsed = parseUrlSafely(rawUrl);
  2875. if (!parsed) return false;
  2876. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  2877. if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
  2878. if (!['/auth/callback', '/codex/callback'].includes(parsed.pathname)) return false;
  2879. const code = (parsed.searchParams.get('code') || '').trim();
  2880. const state = (parsed.searchParams.get('state') || '').trim();
  2881. return Boolean(code && state);
  2882. }
  2883. function isLocalCpaUrl(rawUrl) {
  2884. const parsed = parseUrlSafely(rawUrl);
  2885. if (!parsed) return false;
  2886. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  2887. return ['localhost', '127.0.0.1'].includes(parsed.hostname);
  2888. }
  2889. function shouldBypassStep9ForLocalCpa(state) {
  2890. return normalizeLocalCpaStep9Mode(state?.localCpaStep9Mode) === 'bypass'
  2891. && Boolean(state?.localhostUrl)
  2892. && isLocalCpaUrl(state?.vpsUrl);
  2893. }
  2894. function shouldSkipLoginVerificationForCpaCallback(state) {
  2895. return getPanelMode(state) === 'cpa'
  2896. && normalizeCpaCallbackMode(state?.cpaCallbackMode) === 'step6';
  2897. }
  2898. function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
  2899. const candidate = parseUrlSafely(candidateUrl);
  2900. if (!candidate) return false;
  2901. const reference = parseUrlSafely(referenceUrl);
  2902. switch (source) {
  2903. case 'signup-page':
  2904. return isSignupPageHost(candidate.hostname);
  2905. case 'duck-mail':
  2906. return candidate.hostname === 'duckduckgo.com' && candidate.pathname.startsWith('/email/');
  2907. case 'qq-mail':
  2908. return candidate.hostname === 'mail.qq.com' || candidate.hostname === 'wx.mail.qq.com';
  2909. case 'mail-163':
  2910. return is163MailHost(candidate.hostname);
  2911. case 'gmail-mail':
  2912. return candidate.hostname === 'mail.google.com';
  2913. case 'inbucket-mail':
  2914. return Boolean(reference)
  2915. && candidate.origin === reference.origin
  2916. && candidate.pathname.startsWith('/m/');
  2917. case 'mail-2925':
  2918. return candidate.hostname === '2925.com' || candidate.hostname === 'www.2925.com';
  2919. case 'vps-panel':
  2920. return Boolean(reference)
  2921. && candidate.origin === reference.origin
  2922. && candidate.pathname === reference.pathname;
  2923. case 'sub2api-panel':
  2924. return Boolean(reference)
  2925. && candidate.origin === reference.origin
  2926. && (
  2927. candidate.pathname.startsWith('/admin/accounts')
  2928. || candidate.pathname.startsWith('/login')
  2929. || candidate.pathname === '/'
  2930. );
  2931. default:
  2932. return false;
  2933. }
  2934. }
  2935. async function rememberSourceLastUrl(source, url) {
  2936. if (!source || !url) return;
  2937. const state = await getState();
  2938. const sourceLastUrls = { ...(state.sourceLastUrls || {}) };
  2939. sourceLastUrls[source] = url;
  2940. await setState({ sourceLastUrls });
  2941. }
  2942. async function closeConflictingTabsForSource(source, currentUrl, options = {}) {
  2943. const { excludeTabIds = [] } = options;
  2944. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  2945. const state = await getState();
  2946. const lastUrl = state.sourceLastUrls?.[source];
  2947. const referenceUrls = [currentUrl, lastUrl].filter(Boolean);
  2948. if (!referenceUrls.length) return;
  2949. const tabs = await chrome.tabs.query({});
  2950. const matchedIds = tabs
  2951. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  2952. .filter((tab) => referenceUrls.some((refUrl) => matchesSourceUrlFamily(source, tab.url, refUrl)))
  2953. .map(tab => tab.id);
  2954. if (!matchedIds.length) return;
  2955. await chrome.tabs.remove(matchedIds).catch(() => { });
  2956. const registry = await getTabRegistry();
  2957. if (registry[source]?.tabId && matchedIds.includes(registry[source].tabId)) {
  2958. registry[source] = null;
  2959. await setState({ tabRegistry: registry });
  2960. }
  2961. await addLog(`已关闭 ${matchedIds.length} 个旧的${getSourceLabel(source)}标签页。`, 'info');
  2962. }
  2963. function isLocalhostOAuthCallbackTabMatch(callbackUrl, candidateUrl) {
  2964. if (!isLocalhostOAuthCallbackUrl(callbackUrl) || !isLocalhostOAuthCallbackUrl(candidateUrl)) {
  2965. return false;
  2966. }
  2967. const callback = parseUrlSafely(callbackUrl);
  2968. const candidate = parseUrlSafely(candidateUrl);
  2969. if (!callback || !candidate) return false;
  2970. return callback.origin === candidate.origin
  2971. && callback.pathname === candidate.pathname
  2972. && callback.searchParams.get('code') === candidate.searchParams.get('code')
  2973. && callback.searchParams.get('state') === candidate.searchParams.get('state');
  2974. }
  2975. async function closeLocalhostCallbackTabs(callbackUrl, options = {}) {
  2976. if (!isLocalhostOAuthCallbackUrl(callbackUrl)) return 0;
  2977. const { excludeTabIds = [] } = options;
  2978. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  2979. const tabs = await chrome.tabs.query({});
  2980. const matchedIds = tabs
  2981. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  2982. .filter((tab) => isLocalhostOAuthCallbackTabMatch(callbackUrl, tab.url))
  2983. .map((tab) => tab.id);
  2984. if (!matchedIds.length) return 0;
  2985. await chrome.tabs.remove(matchedIds).catch(() => { });
  2986. const registry = await getTabRegistry();
  2987. if (registry['signup-page']?.tabId && matchedIds.includes(registry['signup-page'].tabId)) {
  2988. registry['signup-page'] = null;
  2989. await setState({ tabRegistry: registry });
  2990. }
  2991. await addLog(`已关闭 ${matchedIds.length} 个匹配当前 OAuth callback 的 localhost 残留标签页。`, 'info');
  2992. return matchedIds.length;
  2993. }
  2994. function buildLocalhostCleanupPrefix(rawUrl) {
  2995. if (!isLocalhostOAuthCallbackUrl(rawUrl)) return '';
  2996. const parsed = parseUrlSafely(rawUrl);
  2997. if (!parsed) return '';
  2998. const segments = parsed.pathname.split('/').filter(Boolean);
  2999. if (!segments.length) {
  3000. return parsed.origin;
  3001. }
  3002. return `${parsed.origin}/${segments[0]}`;
  3003. }
  3004. async function closeTabsByUrlPrefix(prefix, options = {}) {
  3005. if (!prefix) return 0;
  3006. const { excludeTabIds = [], excludeUrls = [], excludeLocalhostCallbacks = false } = options;
  3007. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  3008. const excludedUrls = new Set((Array.isArray(excludeUrls) ? excludeUrls : []).filter(Boolean));
  3009. const tabs = await chrome.tabs.query({});
  3010. const matchedIds = tabs
  3011. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  3012. .filter((tab) => typeof tab.url === 'string' && !excludedUrls.has(tab.url))
  3013. .filter((tab) => !(excludeLocalhostCallbacks && isLocalhostOAuthCallbackUrl(tab.url)))
  3014. .filter((tab) => typeof tab.url === 'string' && tab.url.startsWith(prefix))
  3015. .filter((tab) => !isLocalhostOAuthCallbackUrl(tab.url))
  3016. .map((tab) => tab.id);
  3017. if (!matchedIds.length) return 0;
  3018. await chrome.tabs.remove(matchedIds).catch(() => { });
  3019. await addLog(`已关闭 ${matchedIds.length} 个匹配 ${prefix} 的 localhost 残留标签页。`, 'info');
  3020. return matchedIds.length;
  3021. }
  3022. async function pingContentScriptOnTab(tabId) {
  3023. if (!Number.isInteger(tabId)) return null;
  3024. try {
  3025. return await chrome.tabs.sendMessage(tabId, {
  3026. type: 'PING',
  3027. source: 'background',
  3028. payload: {},
  3029. });
  3030. } catch {
  3031. return null;
  3032. }
  3033. }
  3034. async function waitForTabUrlFamily(source, tabId, referenceUrl, options = {}) {
  3035. const { timeoutMs = 15000, retryDelayMs = 400 } = options;
  3036. const start = Date.now();
  3037. while (Date.now() - start < timeoutMs) {
  3038. try {
  3039. const tab = await chrome.tabs.get(tabId);
  3040. if (matchesSourceUrlFamily(source, tab.url, referenceUrl)) {
  3041. return tab;
  3042. }
  3043. } catch {
  3044. return null;
  3045. }
  3046. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  3047. }
  3048. return null;
  3049. }
  3050. async function waitForTabUrlMatch(tabId, matcher, options = {}) {
  3051. const { timeoutMs = 15000, retryDelayMs = 400 } = options;
  3052. const start = Date.now();
  3053. while (Date.now() - start < timeoutMs) {
  3054. try {
  3055. const tab = await chrome.tabs.get(tabId);
  3056. if (matcher(tab.url || '', tab)) {
  3057. return tab;
  3058. }
  3059. } catch {
  3060. return null;
  3061. }
  3062. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  3063. }
  3064. return null;
  3065. }
  3066. async function ensureContentScriptReadyOnTab(source, tabId, options = {}) {
  3067. const {
  3068. inject = null,
  3069. injectSource = null,
  3070. timeoutMs = 30000,
  3071. retryDelayMs = 700,
  3072. logMessage = '',
  3073. } = options;
  3074. const start = Date.now();
  3075. let lastError = null;
  3076. let logged = false;
  3077. let attempt = 0;
  3078. console.log(
  3079. LOG_PREFIX,
  3080. `[ensureContentScriptReadyOnTab] start ${source} tab=${tabId}, timeout=${timeoutMs}ms, inject=${Array.isArray(inject) ? inject.join(',') : 'none'}`
  3081. );
  3082. while (Date.now() - start < timeoutMs) {
  3083. attempt += 1;
  3084. const pong = await pingContentScriptOnTab(tabId);
  3085. if (pong?.ok && (!pong.source || pong.source === source)) {
  3086. console.log(
  3087. LOG_PREFIX,
  3088. `[ensureContentScriptReadyOnTab] ready ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  3089. );
  3090. await registerTab(source, tabId);
  3091. return;
  3092. }
  3093. if (!inject || !inject.length) {
  3094. throw new Error(`${getSourceLabel(source)} 内容脚本未就绪,且未提供可用的注入文件。`);
  3095. }
  3096. const registry = await getTabRegistry();
  3097. if (registry[source]) {
  3098. registry[source].ready = false;
  3099. await setState({ tabRegistry: registry });
  3100. }
  3101. try {
  3102. if (injectSource) {
  3103. await chrome.scripting.executeScript({
  3104. target: { tabId },
  3105. func: (injectedSource) => {
  3106. window.__MULTIPAGE_SOURCE = injectedSource;
  3107. },
  3108. args: [injectSource],
  3109. });
  3110. }
  3111. await chrome.scripting.executeScript({
  3112. target: { tabId },
  3113. files: inject,
  3114. });
  3115. } catch (err) {
  3116. lastError = err;
  3117. console.warn(
  3118. LOG_PREFIX,
  3119. `[ensureContentScriptReadyOnTab] inject attempt ${attempt} failed for ${source} tab=${tabId}: ${err?.message || err}`
  3120. );
  3121. }
  3122. const pongAfterInject = await pingContentScriptOnTab(tabId);
  3123. if (pongAfterInject?.ok && (!pongAfterInject.source || pongAfterInject.source === source)) {
  3124. console.log(
  3125. LOG_PREFIX,
  3126. `[ensureContentScriptReadyOnTab] ready after inject ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  3127. );
  3128. await registerTab(source, tabId);
  3129. return;
  3130. }
  3131. if (logMessage && !logged) {
  3132. console.warn(
  3133. LOG_PREFIX,
  3134. `[ensureContentScriptReadyOnTab] ${source} tab=${tabId} still not ready after ${Date.now() - start}ms`
  3135. );
  3136. await addLog(logMessage, 'warn');
  3137. logged = true;
  3138. }
  3139. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  3140. }
  3141. throw lastError || new Error(`${getSourceLabel(source)} 内容脚本长时间未就绪。`);
  3142. }
  3143. // ============================================================
  3144. // Command Queue (for content scripts not yet ready)
  3145. // ============================================================
  3146. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  3147. function getContentScriptResponseTimeoutMs(message) {
  3148. if (!message || typeof message !== 'object') {
  3149. return 30000;
  3150. }
  3151. if (message.type === 'EXECUTE_STEP' && Number(message.step) === 6) {
  3152. return 75000;
  3153. }
  3154. if (message.type === 'POLL_EMAIL') {
  3155. const maxAttempts = Math.max(1, Number(message.payload?.maxAttempts) || 1);
  3156. const intervalMs = Math.max(0, Number(message.payload?.intervalMs) || 0);
  3157. return Math.max(45000, maxAttempts * intervalMs + 25000);
  3158. }
  3159. if (message.type === 'FILL_CODE') {
  3160. return Number(message.step) === 7 ? 45000 : 30000;
  3161. }
  3162. if (message.type === 'PREPARE_SIGNUP_VERIFICATION') {
  3163. return 45000;
  3164. }
  3165. return 30000;
  3166. }
  3167. function getMessageDebugLabel(source, message, tabId = null) {
  3168. const parts = [source || 'unknown', message?.type || 'UNKNOWN'];
  3169. if (Number.isInteger(message?.step)) {
  3170. parts.push(`step=${message.step}`);
  3171. }
  3172. if (Number.isInteger(tabId)) {
  3173. parts.push(`tab=${tabId}`);
  3174. }
  3175. return parts.join(' ');
  3176. }
  3177. function summarizeMessageResultForDebug(result) {
  3178. if (result === undefined) return 'undefined';
  3179. if (result === null) return 'null';
  3180. if (typeof result !== 'object') return JSON.stringify(result);
  3181. const summary = {};
  3182. for (const key of ['ok', 'error', 'stopped', 'source', 'step']) {
  3183. if (key in result) summary[key] = result[key];
  3184. }
  3185. if (result.payload && typeof result.payload === 'object') {
  3186. summary.payloadKeys = Object.keys(result.payload);
  3187. }
  3188. return JSON.stringify(summary);
  3189. }
  3190. function sendTabMessageWithTimeout(tabId, source, message, responseTimeoutMs = getContentScriptResponseTimeoutMs(message)) {
  3191. return new Promise((resolve, reject) => {
  3192. let settled = false;
  3193. const startedAt = Date.now();
  3194. const debugLabel = getMessageDebugLabel(source, message, tabId);
  3195. console.log(LOG_PREFIX, `[sendTabMessageWithTimeout] dispatch ${debugLabel}, timeout=${responseTimeoutMs}ms`);
  3196. const timer = setTimeout(() => {
  3197. if (settled) return;
  3198. settled = true;
  3199. const seconds = Math.ceil(responseTimeoutMs / 1000);
  3200. console.warn(LOG_PREFIX, `[sendTabMessageWithTimeout] timeout ${debugLabel} after ${Date.now() - startedAt}ms`);
  3201. reject(new Error(`Content script on ${source} did not respond in ${seconds}s. Try refreshing the tab and retry.`));
  3202. }, responseTimeoutMs);
  3203. chrome.tabs.sendMessage(tabId, message)
  3204. .then((value) => {
  3205. const elapsed = Date.now() - startedAt;
  3206. if (settled) {
  3207. console.warn(
  3208. LOG_PREFIX,
  3209. `[sendTabMessageWithTimeout] late response ignored for ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  3210. );
  3211. return;
  3212. }
  3213. settled = true;
  3214. clearTimeout(timer);
  3215. console.log(
  3216. LOG_PREFIX,
  3217. `[sendTabMessageWithTimeout] response ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  3218. );
  3219. resolve(value);
  3220. })
  3221. .catch((error) => {
  3222. const elapsed = Date.now() - startedAt;
  3223. const errorMessage = error?.message || String(error);
  3224. if (settled) {
  3225. console.warn(
  3226. LOG_PREFIX,
  3227. `[sendTabMessageWithTimeout] late rejection ignored for ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  3228. );
  3229. return;
  3230. }
  3231. settled = true;
  3232. clearTimeout(timer);
  3233. console.warn(
  3234. LOG_PREFIX,
  3235. `[sendTabMessageWithTimeout] rejection ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  3236. );
  3237. reject(error);
  3238. });
  3239. });
  3240. }
  3241. function queueCommand(source, message, timeout = 15000) {
  3242. return new Promise((resolve, reject) => {
  3243. const timer = setTimeout(() => {
  3244. pendingCommands.delete(source);
  3245. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  3246. console.error(LOG_PREFIX, err);
  3247. reject(new Error(err));
  3248. }, timeout);
  3249. pendingCommands.set(source, { message, resolve, reject, timer });
  3250. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  3251. });
  3252. }
  3253. function flushCommand(source, tabId) {
  3254. const pending = pendingCommands.get(source);
  3255. if (pending) {
  3256. clearTimeout(pending.timer);
  3257. pendingCommands.delete(source);
  3258. sendTabMessageWithTimeout(tabId, source, pending.message).then(pending.resolve).catch(pending.reject);
  3259. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  3260. }
  3261. }
  3262. function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
  3263. for (const [source, pending] of pendingCommands.entries()) {
  3264. clearTimeout(pending.timer);
  3265. pending.reject(new Error(reason));
  3266. pendingCommands.delete(source);
  3267. console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
  3268. }
  3269. }
  3270. // ============================================================
  3271. // Reuse or create tab
  3272. // ============================================================
  3273. async function reuseOrCreateTab(source, url, options = {}) {
  3274. const alive = await isTabAlive(source);
  3275. if (alive) {
  3276. const tabId = await getTabId(source);
  3277. await closeConflictingTabsForSource(source, url, { excludeTabIds: [tabId] });
  3278. const currentTab = await chrome.tabs.get(tabId);
  3279. const sameUrl = currentTab.url === url;
  3280. const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
  3281. const registry = await getTabRegistry();
  3282. if (sameUrl) {
  3283. await chrome.tabs.update(tabId, { active: true });
  3284. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
  3285. if (shouldReloadOnReuse) {
  3286. if (registry[source]) registry[source].ready = false;
  3287. await setState({ tabRegistry: registry });
  3288. await chrome.tabs.reload(tabId);
  3289. await new Promise((resolve) => {
  3290. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  3291. const listener = (tid, info) => {
  3292. if (tid === tabId && info.status === 'complete') {
  3293. chrome.tabs.onUpdated.removeListener(listener);
  3294. clearTimeout(timer);
  3295. resolve();
  3296. }
  3297. };
  3298. chrome.tabs.onUpdated.addListener(listener);
  3299. });
  3300. }
  3301. // For dynamically injected pages like the VPS panel, re-inject immediately.
  3302. if (options.inject) {
  3303. if (registry[source]) registry[source].ready = false;
  3304. await setState({ tabRegistry: registry });
  3305. if (options.injectSource) {
  3306. await chrome.scripting.executeScript({
  3307. target: { tabId },
  3308. func: (injectedSource) => {
  3309. window.__MULTIPAGE_SOURCE = injectedSource;
  3310. },
  3311. args: [options.injectSource],
  3312. });
  3313. }
  3314. await chrome.scripting.executeScript({
  3315. target: { tabId },
  3316. files: options.inject,
  3317. });
  3318. await new Promise(r => setTimeout(r, 500));
  3319. }
  3320. await rememberSourceLastUrl(source, url);
  3321. return tabId;
  3322. }
  3323. // Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
  3324. if (registry[source]) registry[source].ready = false;
  3325. await setState({ tabRegistry: registry });
  3326. // Navigate existing tab to new URL
  3327. await chrome.tabs.update(tabId, { url, active: true });
  3328. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
  3329. // Wait for page load complete (with 30s timeout)
  3330. await new Promise((resolve) => {
  3331. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  3332. const listener = (tid, info) => {
  3333. if (tid === tabId && info.status === 'complete') {
  3334. chrome.tabs.onUpdated.removeListener(listener);
  3335. clearTimeout(timer);
  3336. resolve();
  3337. }
  3338. };
  3339. chrome.tabs.onUpdated.addListener(listener);
  3340. });
  3341. // If dynamic injection needed (VPS panel), re-inject after navigation
  3342. if (options.inject) {
  3343. if (options.injectSource) {
  3344. await chrome.scripting.executeScript({
  3345. target: { tabId },
  3346. func: (injectedSource) => {
  3347. window.__MULTIPAGE_SOURCE = injectedSource;
  3348. },
  3349. args: [options.injectSource],
  3350. });
  3351. }
  3352. await chrome.scripting.executeScript({
  3353. target: { tabId },
  3354. files: options.inject,
  3355. });
  3356. }
  3357. // Wait a bit for content script to inject and send READY
  3358. await new Promise(r => setTimeout(r, 500));
  3359. await rememberSourceLastUrl(source, url);
  3360. return tabId;
  3361. }
  3362. // Create new tab
  3363. await closeConflictingTabsForSource(source, url);
  3364. const tab = await chrome.tabs.create({ url, active: true });
  3365. console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
  3366. // If dynamic injection needed (VPS panel), inject scripts after load
  3367. if (options.inject) {
  3368. await new Promise((resolve) => {
  3369. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  3370. const listener = (tabId, info) => {
  3371. if (tabId === tab.id && info.status === 'complete') {
  3372. chrome.tabs.onUpdated.removeListener(listener);
  3373. clearTimeout(timer);
  3374. resolve();
  3375. }
  3376. };
  3377. chrome.tabs.onUpdated.addListener(listener);
  3378. });
  3379. if (options.injectSource) {
  3380. await chrome.scripting.executeScript({
  3381. target: { tabId: tab.id },
  3382. func: (injectedSource) => {
  3383. window.__MULTIPAGE_SOURCE = injectedSource;
  3384. },
  3385. args: [options.injectSource],
  3386. });
  3387. }
  3388. await chrome.scripting.executeScript({
  3389. target: { tabId: tab.id },
  3390. files: options.inject,
  3391. });
  3392. }
  3393. await rememberSourceLastUrl(source, url);
  3394. return tab.id;
  3395. }
  3396. // ============================================================
  3397. // Send command to content script (with readiness check)
  3398. // ============================================================
  3399. async function sendToContentScript(source, message, options = {}) {
  3400. throwIfStopped();
  3401. const { responseTimeoutMs = getContentScriptResponseTimeoutMs(message) } = options;
  3402. const registry = await getTabRegistry();
  3403. const entry = registry[source];
  3404. if (!entry || !entry.ready) {
  3405. throwIfStopped();
  3406. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  3407. return queueCommand(source, message);
  3408. }
  3409. // Verify tab is still alive
  3410. const alive = await isTabAlive(source);
  3411. throwIfStopped();
  3412. if (!alive) {
  3413. // Tab was closed — queue the command, it will be sent when tab is reopened
  3414. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  3415. return queueCommand(source, message);
  3416. }
  3417. throwIfStopped();
  3418. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  3419. return sendTabMessageWithTimeout(entry.tabId, source, message, responseTimeoutMs);
  3420. }
  3421. async function sendToContentScriptResilient(source, message, options = {}) {
  3422. const { timeoutMs = 30000, retryDelayMs = 600, logMessage = '' } = options;
  3423. const start = Date.now();
  3424. let lastError = null;
  3425. let logged = false;
  3426. let attempt = 0;
  3427. const debugLabel = getMessageDebugLabel(source, message);
  3428. console.log(
  3429. LOG_PREFIX,
  3430. `[sendToContentScriptResilient] start ${debugLabel}, totalTimeout=${timeoutMs}ms, retryDelay=${retryDelayMs}ms`
  3431. );
  3432. while (Date.now() - start < timeoutMs) {
  3433. throwIfStopped();
  3434. attempt += 1;
  3435. try {
  3436. console.log(
  3437. LOG_PREFIX,
  3438. `[sendToContentScriptResilient] attempt ${attempt} -> ${debugLabel}, elapsed=${Date.now() - start}ms`
  3439. );
  3440. const result = await sendToContentScript(source, message);
  3441. console.log(
  3442. LOG_PREFIX,
  3443. `[sendToContentScriptResilient] success ${debugLabel} on attempt ${attempt} after ${Date.now() - start}ms`
  3444. );
  3445. return result;
  3446. } catch (err) {
  3447. const retryable = isRetryableContentScriptTransportError(err);
  3448. console.warn(
  3449. LOG_PREFIX,
  3450. `[sendToContentScriptResilient] attempt ${attempt} failed for ${debugLabel}, retryable=${retryable}, elapsed=${Date.now() - start}ms: ${err?.message || err}`
  3451. );
  3452. if (!retryable) {
  3453. throw err;
  3454. }
  3455. lastError = err;
  3456. if (logMessage && !logged) {
  3457. await addLog(logMessage, 'warn');
  3458. logged = true;
  3459. }
  3460. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  3461. }
  3462. }
  3463. throw lastError || new Error(`等待 ${getSourceLabel(source)} 重新就绪超时。`);
  3464. }
  3465. async function sendToMailContentScriptResilient(mail, message, options = {}) {
  3466. const { timeoutMs = 45000, maxRecoveryAttempts = 2 } = options;
  3467. const start = Date.now();
  3468. let lastError = null;
  3469. let recoveries = 0;
  3470. let logged = false;
  3471. while (Date.now() - start < timeoutMs) {
  3472. throwIfStopped();
  3473. try {
  3474. return await sendToContentScript(mail.source, message);
  3475. } catch (err) {
  3476. if (!isRetryableContentScriptTransportError(err)) {
  3477. throw err;
  3478. }
  3479. lastError = err;
  3480. if (!logged) {
  3481. await addLog(`步骤 ${message.step}:${mail.label} 页面通信异常,正在尝试让邮箱页重新就绪...`, 'warn');
  3482. logged = true;
  3483. }
  3484. if (recoveries >= maxRecoveryAttempts) {
  3485. break;
  3486. }
  3487. recoveries += 1;
  3488. await reuseOrCreateTab(mail.source, mail.url, {
  3489. inject: mail.inject,
  3490. injectSource: mail.injectSource,
  3491. reloadIfSameUrl: true,
  3492. });
  3493. await new Promise((resolve) => setTimeout(resolve, 800));
  3494. }
  3495. }
  3496. throw lastError || new Error(`${mail.label} 页面未能重新就绪。`);
  3497. }
  3498. // ============================================================
  3499. // Logging
  3500. // ============================================================
  3501. async function addLog(message, level = 'info') {
  3502. const state = await getState();
  3503. const logs = state.logs || [];
  3504. const entry = { message, level, timestamp: Date.now() };
  3505. logs.push(entry);
  3506. // Keep last 500 logs
  3507. if (logs.length > 500) logs.splice(0, logs.length - 500);
  3508. await setState({ logs });
  3509. // Broadcast to side panel
  3510. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => { });
  3511. }
  3512. function getStep8CallbackUrlFromNavigation(details, signupTabId) {
  3513. if (!Number.isInteger(signupTabId) || !details) return '';
  3514. if (details.tabId !== signupTabId) return '';
  3515. if (details.frameId !== 0) return '';
  3516. return isLocalhostOAuthCallbackUrl(details.url) ? details.url : '';
  3517. }
  3518. function getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId) {
  3519. if (!Number.isInteger(signupTabId) || tabId !== signupTabId) return '';
  3520. const candidates = [changeInfo?.url, tab?.url];
  3521. for (const candidate of candidates) {
  3522. if (isLocalhostOAuthCallbackUrl(candidate)) {
  3523. return candidate;
  3524. }
  3525. }
  3526. return '';
  3527. }
  3528. function getSourceLabel(source) {
  3529. const labels = {
  3530. 'gmail-mail': 'Gmail 邮箱',
  3531. 'sidepanel': '侧边栏',
  3532. 'signup-page': '认证页',
  3533. 'vps-panel': 'CPA 面板',
  3534. 'sub2api-panel': 'SUB2API 后台',
  3535. 'qq-mail': 'QQ 邮箱',
  3536. 'mail-163': '163 邮箱',
  3537. 'mail-2925': '2925 邮箱',
  3538. 'inbucket-mail': 'Inbucket 邮箱',
  3539. 'duck-mail': 'Duck 邮箱',
  3540. 'hotmail-api': 'Hotmail(API对接/本地助手)',
  3541. 'luckmail-api': 'LuckMail(API 购邮)',
  3542. 'cloudflare-temp-email': 'Cloudflare Temp Email',
  3543. };
  3544. return labels[source] || source || '未知来源';
  3545. }
  3546. // ============================================================
  3547. // Step Status Management
  3548. // ============================================================
  3549. async function setStepStatus(step, status) {
  3550. const state = await getState();
  3551. const statuses = { ...state.stepStatuses };
  3552. statuses[step] = status;
  3553. await setState({ stepStatuses: statuses, currentStep: step });
  3554. // Broadcast to side panel
  3555. chrome.runtime.sendMessage({
  3556. type: 'STEP_STATUS_CHANGED',
  3557. payload: { step, status },
  3558. }).catch(() => { });
  3559. }
  3560. function isStopError(error) {
  3561. const message = typeof error === 'string' ? error : error?.message;
  3562. return message === STOP_ERROR_MESSAGE;
  3563. }
  3564. function isRetryableContentScriptTransportError(error) {
  3565. const message = String(typeof error === 'string' ? error : error?.message || '');
  3566. 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);
  3567. }
  3568. function getErrorMessage(error) {
  3569. return String(typeof error === 'string' ? error : error?.message || '');
  3570. }
  3571. function isVerificationMailPollingError(error) {
  3572. const message = getErrorMessage(error);
  3573. return /未在 .*邮箱中找到新的匹配邮件|未在 Hotmail 收件箱中找到新的匹配验证码|邮箱轮询结束,但未获取到验证码|无法获取新的(?:注册|登录)验证码|页面未能重新就绪|页面通信异常|did not respond in \d+s/i.test(message);
  3574. }
  3575. function getLoginAuthStateLabel(state) {
  3576. switch (state) {
  3577. case 'verification_page':
  3578. return '登录验证码页';
  3579. case 'password_page':
  3580. return '密码页';
  3581. case 'email_page':
  3582. return '邮箱输入页';
  3583. case 'login_timeout_error_page':
  3584. return '登录超时报错页';
  3585. case 'oauth_consent_page':
  3586. return 'OAuth 授权页';
  3587. case 'add_phone_page':
  3588. return '手机号页';
  3589. default:
  3590. return '未知页面';
  3591. }
  3592. }
  3593. function isRestartCurrentAttemptError(error) {
  3594. const message = String(typeof error === 'string' ? error : error?.message || '');
  3595. return /当前邮箱已存在,需要重新开始新一轮/.test(message);
  3596. }
  3597. function isStep9RecoverableAuthError(error) {
  3598. const message = String(typeof error === 'string' ? error : error?.message || '');
  3599. return /STEP9_OAUTH_RETRY::/i.test(message)
  3600. || isRecoverableStep9AuthFailure(message);
  3601. }
  3602. function isLegacyStep9RecoverableAuthError(error) {
  3603. const message = String(typeof error === 'string' ? error : error?.message || '');
  3604. return /STEP9_OAUTH_TIMEOUT::|认证失败:\s*Timeout waiting for OAuth callback/i.test(message);
  3605. }
  3606. function isStepDoneStatus(status) {
  3607. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  3608. }
  3609. function getFirstUnfinishedStep(statuses = {}) {
  3610. for (let step = 1; step <= 9; step++) {
  3611. if (!isStepDoneStatus(statuses[step] || 'pending')) {
  3612. return step;
  3613. }
  3614. }
  3615. return null;
  3616. }
  3617. function hasSavedProgress(statuses = {}) {
  3618. return Object.values({ ...DEFAULT_STATE.stepStatuses, ...statuses }).some((status) => status !== 'pending');
  3619. }
  3620. function getDownstreamStateResets(step) {
  3621. if (step <= 1) {
  3622. return {
  3623. oauthUrl: null,
  3624. sub2apiSessionId: null,
  3625. sub2apiOAuthState: null,
  3626. sub2apiGroupId: null,
  3627. sub2apiDraftName: null,
  3628. flowStartTime: null,
  3629. password: null,
  3630. lastEmailTimestamp: null,
  3631. signupVerificationRequestedAt: null,
  3632. loginVerificationRequestedAt: null,
  3633. lastSignupCode: null,
  3634. lastLoginCode: null,
  3635. localhostUrl: null,
  3636. };
  3637. }
  3638. if (step === 2) {
  3639. return {
  3640. password: null,
  3641. lastEmailTimestamp: null,
  3642. signupVerificationRequestedAt: null,
  3643. loginVerificationRequestedAt: null,
  3644. lastSignupCode: null,
  3645. lastLoginCode: null,
  3646. localhostUrl: null,
  3647. };
  3648. }
  3649. if (step === 3 || step === 4) {
  3650. return {
  3651. lastEmailTimestamp: null,
  3652. signupVerificationRequestedAt: null,
  3653. loginVerificationRequestedAt: null,
  3654. lastSignupCode: null,
  3655. lastLoginCode: null,
  3656. localhostUrl: null,
  3657. };
  3658. }
  3659. if (step === 5 || step === 6 || step === 7) {
  3660. return {
  3661. lastLoginCode: null,
  3662. loginVerificationRequestedAt: null,
  3663. localhostUrl: null,
  3664. };
  3665. }
  3666. if (step === 8) {
  3667. return {
  3668. localhostUrl: null,
  3669. };
  3670. }
  3671. return {};
  3672. }
  3673. async function invalidateDownstreamAfterStepRestart(step, options = {}) {
  3674. const { logLabel = `步骤 ${step} 重新执行` } = options;
  3675. const state = await getState();
  3676. const statuses = { ...(state.stepStatuses || {}) };
  3677. const changedSteps = [];
  3678. for (let downstream = step + 1; downstream <= 9; downstream++) {
  3679. if (statuses[downstream] !== 'pending') {
  3680. statuses[downstream] = 'pending';
  3681. changedSteps.push(downstream);
  3682. }
  3683. }
  3684. if (changedSteps.length) {
  3685. await setState({ stepStatuses: statuses });
  3686. for (const downstream of changedSteps) {
  3687. chrome.runtime.sendMessage({
  3688. type: 'STEP_STATUS_CHANGED',
  3689. payload: { step: downstream, status: 'pending' },
  3690. }).catch(() => { });
  3691. }
  3692. await addLog(`${logLabel},已重置后续步骤状态:${changedSteps.join(', ')}`, 'warn');
  3693. }
  3694. const resets = getDownstreamStateResets(step);
  3695. if (Object.keys(resets).length) {
  3696. await setState(resets);
  3697. broadcastDataUpdate(resets);
  3698. }
  3699. }
  3700. function clearStopRequest() {
  3701. stopRequested = false;
  3702. }
  3703. function getRunningSteps(statuses = {}) {
  3704. return Object.entries({ ...DEFAULT_STATE.stepStatuses, ...statuses })
  3705. .filter(([, status]) => status === 'running')
  3706. .map(([step]) => Number(step))
  3707. .sort((a, b) => a - b);
  3708. }
  3709. function getAutoRunStatusPayload(phase, payload = {}) {
  3710. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  3711. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  3712. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  3713. const rawScheduledAt = phase === 'scheduled'
  3714. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  3715. : null;
  3716. const scheduledAt = rawScheduledAt === null ? null : Number(rawScheduledAt);
  3717. const rawCountdownAt = payload.countdownAt ?? payload.autoRunCountdownAt ?? null;
  3718. const countdownAt = rawCountdownAt === null ? null : Number(rawCountdownAt);
  3719. const countdownTitle = payload.countdownTitle === undefined
  3720. ? ''
  3721. : String(payload.countdownTitle || '');
  3722. const countdownNote = payload.countdownNote === undefined
  3723. ? ''
  3724. : String(payload.countdownNote || '');
  3725. const autoRunning = phase === 'scheduled'
  3726. || phase === 'running'
  3727. || phase === 'waiting_step'
  3728. || phase === 'waiting_email'
  3729. || phase === 'retrying'
  3730. || phase === 'waiting_interval';
  3731. return {
  3732. autoRunning,
  3733. autoRunPhase: phase,
  3734. autoRunCurrentRun: currentRun,
  3735. autoRunTotalRuns: totalRuns,
  3736. autoRunAttemptRun: attemptRun,
  3737. scheduledAutoRunAt: Number.isFinite(scheduledAt) ? scheduledAt : null,
  3738. autoRunCountdownAt: Number.isFinite(countdownAt) ? countdownAt : null,
  3739. autoRunCountdownTitle: countdownTitle,
  3740. autoRunCountdownNote: countdownNote,
  3741. };
  3742. }
  3743. async function broadcastAutoRunStatus(phase, payload = {}, extraState = {}) {
  3744. const rawScheduledAt = phase === 'scheduled'
  3745. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  3746. : null;
  3747. const rawCountdownAt = payload.countdownAt ?? payload.autoRunCountdownAt ?? null;
  3748. const statusPayload = {
  3749. phase,
  3750. currentRun: payload.currentRun ?? autoRunCurrentRun,
  3751. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  3752. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  3753. scheduledAt: rawScheduledAt === null ? null : Number(rawScheduledAt),
  3754. countdownAt: rawCountdownAt === null ? null : Number(rawCountdownAt),
  3755. countdownTitle: payload.countdownTitle === undefined ? '' : String(payload.countdownTitle || ''),
  3756. countdownNote: payload.countdownNote === undefined ? '' : String(payload.countdownNote || ''),
  3757. };
  3758. await setState({
  3759. ...extraState,
  3760. ...getAutoRunStatusPayload(phase, statusPayload),
  3761. });
  3762. chrome.runtime.sendMessage({
  3763. type: 'AUTO_RUN_STATUS',
  3764. payload: statusPayload,
  3765. }).catch(() => { });
  3766. }
  3767. function isAutoRunLockedState(state) {
  3768. return Boolean(state.autoRunning)
  3769. && (
  3770. state.autoRunPhase === 'running'
  3771. || state.autoRunPhase === 'waiting_step'
  3772. || state.autoRunPhase === 'retrying'
  3773. || state.autoRunPhase === 'waiting_interval'
  3774. );
  3775. }
  3776. function isAutoRunPausedState(state) {
  3777. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  3778. }
  3779. function isAutoRunScheduledState(state) {
  3780. const plan = normalizeAutoRunTimerPlanFromState(state);
  3781. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  3782. return Boolean(state.autoRunning)
  3783. && state.autoRunPhase === 'scheduled'
  3784. && Number.isFinite(scheduledAt)
  3785. && plan?.kind === AUTO_RUN_TIMER_KIND_SCHEDULED_START;
  3786. }
  3787. function getPendingAutoRunTimerPlan(state = {}) {
  3788. return normalizeAutoRunTimerPlanFromState(state);
  3789. }
  3790. function formatAutoRunScheduleTime(timestamp) {
  3791. return new Date(timestamp).toLocaleString('zh-CN', {
  3792. hour12: false,
  3793. timeZone: DISPLAY_TIMEZONE,
  3794. month: '2-digit',
  3795. day: '2-digit',
  3796. hour: '2-digit',
  3797. minute: '2-digit',
  3798. second: '2-digit',
  3799. });
  3800. }
  3801. async function setAutoRunDelayEnabledState(enabled) {
  3802. const normalized = Boolean(enabled);
  3803. await setPersistentSettings({ autoRunDelayEnabled: normalized });
  3804. await setState({ autoRunDelayEnabled: normalized });
  3805. broadcastDataUpdate({ autoRunDelayEnabled: normalized });
  3806. }
  3807. async function ensureAutoRunTimerAlarm(fireAt) {
  3808. if (!Number.isFinite(fireAt) || fireAt <= Date.now()) {
  3809. return false;
  3810. }
  3811. const existingAlarm = await chrome.alarms.get(AUTO_RUN_TIMER_ALARM_NAME);
  3812. if (!existingAlarm || Math.abs((existingAlarm.scheduledTime || 0) - fireAt) > 1000) {
  3813. await chrome.alarms.clear(AUTO_RUN_TIMER_ALARM_NAME);
  3814. await chrome.alarms.create(AUTO_RUN_TIMER_ALARM_NAME, { when: fireAt });
  3815. }
  3816. return true;
  3817. }
  3818. async function clearAutoRunTimerAlarm() {
  3819. await chrome.alarms.clear(AUTO_RUN_TIMER_ALARM_NAME);
  3820. }
  3821. async function persistAutoRunTimerPlan(plan, extraState = {}) {
  3822. const normalizedPlan = normalizeAutoRunTimerPlan(plan);
  3823. if (!normalizedPlan) {
  3824. throw new Error('自动运行计时计划无效。');
  3825. }
  3826. const statusPayload = getAutoRunTimerStatusPayload(normalizedPlan);
  3827. await broadcastAutoRunStatus(
  3828. statusPayload.phase,
  3829. statusPayload,
  3830. {
  3831. ...extraState,
  3832. autoRunTimerPlan: normalizedPlan,
  3833. scheduledAutoRunPlan: null,
  3834. }
  3835. );
  3836. await ensureAutoRunTimerAlarm(normalizedPlan.fireAt);
  3837. return normalizedPlan;
  3838. }
  3839. function getAutoRunTimerResumeOptions(plan) {
  3840. const normalizedPlan = normalizeAutoRunTimerPlan(plan);
  3841. if (!normalizedPlan) {
  3842. return null;
  3843. }
  3844. if (normalizedPlan.kind === AUTO_RUN_TIMER_KIND_SCHEDULED_START) {
  3845. return {
  3846. loopOptions: {
  3847. autoRunSkipFailures: normalizedPlan.autoRunSkipFailures,
  3848. mode: normalizedPlan.mode,
  3849. },
  3850. statusPayload: {
  3851. currentRun: 0,
  3852. totalRuns: normalizedPlan.totalRuns,
  3853. attemptRun: 0,
  3854. },
  3855. };
  3856. }
  3857. if (normalizedPlan.kind === AUTO_RUN_TIMER_KIND_BETWEEN_ROUNDS) {
  3858. const nextRun = Math.min(normalizedPlan.currentRun + 1, normalizedPlan.totalRuns);
  3859. return {
  3860. loopOptions: {
  3861. autoRunSkipFailures: normalizedPlan.autoRunSkipFailures,
  3862. mode: 'restart',
  3863. resumeCurrentRun: nextRun,
  3864. resumeAttemptRun: 1,
  3865. resumeRoundSummaries: normalizedPlan.roundSummaries,
  3866. },
  3867. statusPayload: {
  3868. currentRun: nextRun,
  3869. totalRuns: normalizedPlan.totalRuns,
  3870. attemptRun: 1,
  3871. },
  3872. };
  3873. }
  3874. return {
  3875. loopOptions: {
  3876. autoRunSkipFailures: normalizedPlan.autoRunSkipFailures,
  3877. mode: 'restart',
  3878. resumeCurrentRun: normalizedPlan.currentRun,
  3879. resumeAttemptRun: normalizedPlan.attemptRun,
  3880. resumeRoundSummaries: normalizedPlan.roundSummaries,
  3881. },
  3882. statusPayload: {
  3883. currentRun: normalizedPlan.currentRun,
  3884. totalRuns: normalizedPlan.totalRuns,
  3885. attemptRun: normalizedPlan.attemptRun,
  3886. },
  3887. };
  3888. }
  3889. let autoRunTimerLaunching = false;
  3890. async function launchAutoRunTimerPlan(trigger = 'alarm', options = {}) {
  3891. const { expectedKinds = [] } = options;
  3892. if (autoRunTimerLaunching) {
  3893. return false;
  3894. }
  3895. autoRunTimerLaunching = true;
  3896. try {
  3897. const state = await getState();
  3898. const plan = getPendingAutoRunTimerPlan(state);
  3899. if (!plan) {
  3900. return false;
  3901. }
  3902. if (expectedKinds.length && !expectedKinds.includes(plan.kind)) {
  3903. return false;
  3904. }
  3905. if (autoRunActive) {
  3906. return false;
  3907. }
  3908. const resumeOptions = getAutoRunTimerResumeOptions(plan);
  3909. if (!resumeOptions) {
  3910. await clearAutoRunTimerAlarm();
  3911. await broadcastAutoRunStatus('idle', {
  3912. currentRun: 0,
  3913. totalRuns: 1,
  3914. attemptRun: 0,
  3915. }, {
  3916. autoRunRoundSummaries: [],
  3917. autoRunTimerPlan: null,
  3918. scheduledAutoRunPlan: null,
  3919. });
  3920. return false;
  3921. }
  3922. await clearAutoRunTimerAlarm();
  3923. autoRunCurrentRun = resumeOptions.statusPayload.currentRun;
  3924. autoRunTotalRuns = plan.totalRuns;
  3925. autoRunAttemptRun = resumeOptions.statusPayload.attemptRun;
  3926. if (plan.kind === AUTO_RUN_TIMER_KIND_SCHEDULED_START && trigger !== 'manual' && state.autoRunDelayEnabled) {
  3927. await setAutoRunDelayEnabledState(false);
  3928. }
  3929. await broadcastAutoRunStatus(
  3930. 'running',
  3931. resumeOptions.statusPayload,
  3932. {
  3933. autoRunSkipFailures: plan.autoRunSkipFailures,
  3934. autoRunRoundSummaries: serializeAutoRunRoundSummaries(plan.totalRuns, plan.roundSummaries),
  3935. autoRunTimerPlan: null,
  3936. scheduledAutoRunPlan: null,
  3937. }
  3938. );
  3939. clearStopRequest();
  3940. let logMessage = '倒计时结束,自动运行开始执行。';
  3941. if (plan.kind === AUTO_RUN_TIMER_KIND_BETWEEN_ROUNDS) {
  3942. logMessage = trigger === 'manual'
  3943. ? '已手动跳过线程间隔,自动流程立即开始下一轮。'
  3944. : '线程间隔结束,自动流程开始下一轮。';
  3945. } else if (plan.kind === AUTO_RUN_TIMER_KIND_BEFORE_RETRY) {
  3946. logMessage = trigger === 'manual'
  3947. ? `已手动跳过线程间隔,立即开始第 ${plan.currentRun}/${plan.totalRuns} 轮第 ${plan.attemptRun} 次尝试。`
  3948. : `线程间隔结束,开始第 ${plan.currentRun}/${plan.totalRuns} 轮第 ${plan.attemptRun} 次尝试。`;
  3949. } else if (trigger === 'manual') {
  3950. logMessage = '已手动跳过倒计时,自动运行立即开始。';
  3951. }
  3952. await addLog(logMessage, 'info');
  3953. startAutoRunLoop(plan.totalRuns, resumeOptions.loopOptions);
  3954. return true;
  3955. } finally {
  3956. autoRunTimerLaunching = false;
  3957. }
  3958. }
  3959. async function scheduleAutoRun(totalRuns, options = {}) {
  3960. const state = await getState();
  3961. if (isAutoRunLockedState(state) || isAutoRunPausedState(state) || autoRunActive) {
  3962. throw new Error('自动运行已在进行中,请先停止后再重新计划。');
  3963. }
  3964. if (getPendingAutoRunTimerPlan(state)) {
  3965. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  3966. }
  3967. const delayMinutes = normalizeAutoRunDelayMinutes(options.delayMinutes);
  3968. const timerPlan = normalizeAutoRunTimerPlan({
  3969. kind: AUTO_RUN_TIMER_KIND_SCHEDULED_START,
  3970. fireAt: Date.now() + delayMinutes * 60 * 1000,
  3971. totalRuns,
  3972. autoRunSkipFailures: options.autoRunSkipFailures,
  3973. mode: options.mode,
  3974. });
  3975. autoRunCurrentRun = 0;
  3976. autoRunTotalRuns = timerPlan.totalRuns;
  3977. autoRunAttemptRun = 0;
  3978. await persistAutoRunTimerPlan(timerPlan, {
  3979. autoRunSkipFailures: timerPlan.autoRunSkipFailures,
  3980. autoRunRoundSummaries: serializeAutoRunRoundSummaries(timerPlan.totalRuns, []),
  3981. });
  3982. await addLog(
  3983. `自动运行已计划:${delayMinutes} 分钟后启动(${formatAutoRunScheduleTime(timerPlan.fireAt)}),目标 ${timerPlan.totalRuns} 轮。`,
  3984. 'info'
  3985. );
  3986. return { ok: true, scheduledAt: timerPlan.fireAt };
  3987. }
  3988. async function cancelScheduledAutoRun(options = {}) {
  3989. const state = await getState();
  3990. const plan = getPendingAutoRunTimerPlan(state);
  3991. if (!plan || plan.kind !== AUTO_RUN_TIMER_KIND_SCHEDULED_START) {
  3992. return false;
  3993. }
  3994. autoRunCurrentRun = 0;
  3995. autoRunTotalRuns = plan.totalRuns;
  3996. autoRunAttemptRun = 0;
  3997. await broadcastAutoRunStatus(
  3998. 'idle',
  3999. {
  4000. currentRun: 0,
  4001. totalRuns: plan.totalRuns,
  4002. attemptRun: 0,
  4003. },
  4004. {
  4005. autoRunRoundSummaries: [],
  4006. autoRunTimerPlan: null,
  4007. scheduledAutoRunPlan: null,
  4008. }
  4009. );
  4010. await clearAutoRunTimerAlarm();
  4011. if (options.logMessage !== false) {
  4012. await addLog(options.logMessage || '已取消自动运行倒计时计划。', 'warn');
  4013. }
  4014. return true;
  4015. }
  4016. async function restoreAutoRunTimerIfNeeded() {
  4017. const state = await getState();
  4018. const plan = getPendingAutoRunTimerPlan(state);
  4019. if (!plan) {
  4020. if (state.autoRunPhase === 'scheduled' || state.autoRunPhase === 'waiting_interval') {
  4021. await clearAutoRunTimerAlarm();
  4022. await broadcastAutoRunStatus('idle', {
  4023. currentRun: 0,
  4024. totalRuns: 1,
  4025. attemptRun: 0,
  4026. }, {
  4027. autoRunRoundSummaries: [],
  4028. autoRunTimerPlan: null,
  4029. scheduledAutoRunPlan: null,
  4030. });
  4031. }
  4032. return;
  4033. }
  4034. if (plan.fireAt <= Date.now()) {
  4035. await launchAutoRunTimerPlan('restore');
  4036. return;
  4037. }
  4038. const statusPayload = getAutoRunTimerStatusPayload(plan);
  4039. await broadcastAutoRunStatus(
  4040. statusPayload.phase,
  4041. statusPayload,
  4042. {
  4043. autoRunSkipFailures: plan.autoRunSkipFailures,
  4044. autoRunRoundSummaries: serializeAutoRunRoundSummaries(plan.totalRuns, plan.roundSummaries),
  4045. autoRunTimerPlan: plan,
  4046. scheduledAutoRunPlan: null,
  4047. }
  4048. );
  4049. await ensureAutoRunTimerAlarm(plan.fireAt);
  4050. }
  4051. async function ensureManualInteractionAllowed(actionLabel) {
  4052. const state = await getState();
  4053. if (isAutoRunLockedState(state)) {
  4054. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  4055. }
  4056. if (isAutoRunPausedState(state)) {
  4057. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  4058. }
  4059. if (isAutoRunScheduledState(state)) {
  4060. throw new Error(`自动流程已计划启动。请先取消计划,或立即开始后再${actionLabel}。`);
  4061. }
  4062. return state;
  4063. }
  4064. async function skipStep(step) {
  4065. const state = await ensureManualInteractionAllowed('跳过步骤');
  4066. if (!Number.isInteger(step) || step < 1 || step > 9) {
  4067. throw new Error(`无效步骤:${step}`);
  4068. }
  4069. const statuses = { ...(state.stepStatuses || {}) };
  4070. const currentStatus = statuses[step];
  4071. if (currentStatus === 'running') {
  4072. throw new Error(`步骤 ${step} 正在运行中,不能跳过。`);
  4073. }
  4074. if (isStepDoneStatus(currentStatus)) {
  4075. throw new Error(`步骤 ${step} 已完成,无需再跳过。`);
  4076. }
  4077. if (step > 1) {
  4078. const prevStatus = statuses[step - 1];
  4079. if (!isStepDoneStatus(prevStatus)) {
  4080. throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`);
  4081. }
  4082. }
  4083. await setStepStatus(step, 'skipped');
  4084. await addLog(`步骤 ${step} 已跳过`, 'warn');
  4085. if (step === 1) {
  4086. const latestState = await getState();
  4087. const step2Status = latestState.stepStatuses?.[2];
  4088. if (!isStepDoneStatus(step2Status) && step2Status !== 'running') {
  4089. await setStepStatus(2, 'skipped');
  4090. await addLog('步骤 1 已跳过,步骤 2 也已同时跳过。', 'warn');
  4091. }
  4092. }
  4093. return { ok: true, step, status: 'skipped' };
  4094. }
  4095. function throwIfStopped() {
  4096. if (stopRequested) {
  4097. throw new Error(STOP_ERROR_MESSAGE);
  4098. }
  4099. }
  4100. async function sleepWithStop(ms) {
  4101. const start = Date.now();
  4102. while (Date.now() - start < ms) {
  4103. throwIfStopped();
  4104. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  4105. }
  4106. }
  4107. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  4108. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  4109. await sleepWithStop(duration);
  4110. }
  4111. async function clickWithDebugger(tabId, rect) {
  4112. throwIfStopped();
  4113. if (!tabId) {
  4114. throw new Error('未找到用于调试点击的认证页面标签页。');
  4115. }
  4116. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  4117. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  4118. }
  4119. const target = { tabId };
  4120. try {
  4121. await chrome.debugger.attach(target, '1.3');
  4122. } catch (err) {
  4123. throw new Error(
  4124. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  4125. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  4126. );
  4127. }
  4128. try {
  4129. throwIfStopped();
  4130. const x = Math.round(rect.centerX);
  4131. const y = Math.round(rect.centerY);
  4132. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  4133. throwIfStopped();
  4134. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  4135. type: 'mouseMoved',
  4136. x,
  4137. y,
  4138. button: 'none',
  4139. buttons: 0,
  4140. clickCount: 0,
  4141. });
  4142. throwIfStopped();
  4143. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  4144. type: 'mousePressed',
  4145. x,
  4146. y,
  4147. button: 'left',
  4148. buttons: 1,
  4149. clickCount: 1,
  4150. });
  4151. throwIfStopped();
  4152. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  4153. type: 'mouseReleased',
  4154. x,
  4155. y,
  4156. button: 'left',
  4157. buttons: 0,
  4158. clickCount: 1,
  4159. });
  4160. } finally {
  4161. await chrome.debugger.detach(target).catch(() => { });
  4162. }
  4163. }
  4164. async function broadcastStopToContentScripts() {
  4165. const registry = await getTabRegistry();
  4166. for (const entry of Object.values(registry)) {
  4167. if (!entry?.tabId) continue;
  4168. try {
  4169. await chrome.tabs.sendMessage(entry.tabId, {
  4170. type: 'STOP_FLOW',
  4171. source: 'background',
  4172. payload: {},
  4173. });
  4174. } catch { }
  4175. }
  4176. }
  4177. let stopRequested = false;
  4178. // ============================================================
  4179. // Message Handler (central router)
  4180. // ============================================================
  4181. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  4182. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  4183. handleMessage(message, sender).then(response => {
  4184. sendResponse(response);
  4185. }).catch(err => {
  4186. console.error(LOG_PREFIX, 'Handler error:', err);
  4187. sendResponse({ error: err.message });
  4188. });
  4189. return true; // async response
  4190. });
  4191. async function handleMessage(message, sender) {
  4192. switch (message.type) {
  4193. case 'CONTENT_SCRIPT_READY': {
  4194. const tabId = sender.tab?.id;
  4195. if (tabId && message.source) {
  4196. await registerTab(message.source, tabId);
  4197. flushCommand(message.source, tabId);
  4198. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  4199. }
  4200. return { ok: true };
  4201. }
  4202. case 'LOG': {
  4203. const { message: msg, level } = message.payload;
  4204. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  4205. return { ok: true };
  4206. }
  4207. case 'STEP_COMPLETE': {
  4208. if (stopRequested) {
  4209. await setStepStatus(message.step, 'stopped');
  4210. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  4211. return { ok: true };
  4212. }
  4213. await setStepStatus(message.step, 'completed');
  4214. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  4215. await handleStepData(message.step, message.payload);
  4216. notifyStepComplete(message.step, message.payload);
  4217. return { ok: true };
  4218. }
  4219. case 'STEP_ERROR': {
  4220. if (isStopError(message.error)) {
  4221. await setStepStatus(message.step, 'stopped');
  4222. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  4223. notifyStepError(message.step, message.error);
  4224. } else {
  4225. await setStepStatus(message.step, 'failed');
  4226. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  4227. notifyStepError(message.step, message.error);
  4228. }
  4229. return { ok: true };
  4230. }
  4231. case 'GET_STATE': {
  4232. return await getState();
  4233. }
  4234. case 'RESET': {
  4235. clearStopRequest();
  4236. await clearAutoRunTimerAlarm();
  4237. await resetState();
  4238. await addLog('流程已重置', 'info');
  4239. return { ok: true };
  4240. }
  4241. case 'EXECUTE_STEP': {
  4242. clearStopRequest();
  4243. if (message.source === 'sidepanel') {
  4244. await ensureManualInteractionAllowed('手动执行步骤');
  4245. }
  4246. const step = message.payload.step;
  4247. if (message.source === 'sidepanel') {
  4248. await invalidateDownstreamAfterStepRestart(step, { logLabel: `步骤 ${step} 重新执行` });
  4249. }
  4250. // Save email if provided (from side panel step 3)
  4251. if (message.payload.email) {
  4252. await setEmailState(message.payload.email);
  4253. }
  4254. if (message.payload.emailPrefix !== undefined) {
  4255. await setPersistentSettings({ emailPrefix: message.payload.emailPrefix });
  4256. await setState({ emailPrefix: message.payload.emailPrefix });
  4257. }
  4258. if (doesStepUseCompletionSignal(step)) {
  4259. await executeStepViaCompletionSignal(step);
  4260. } else {
  4261. await executeStep(step);
  4262. }
  4263. return { ok: true };
  4264. }
  4265. case 'AUTO_RUN': {
  4266. clearStopRequest();
  4267. const state = await getState();
  4268. if (getPendingAutoRunTimerPlan(state)) {
  4269. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  4270. }
  4271. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  4272. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  4273. const mode = message.payload?.mode === 'continue' ? 'continue' : 'restart';
  4274. await setState({ autoRunSkipFailures });
  4275. startAutoRunLoop(totalRuns, { autoRunSkipFailures, mode });
  4276. return { ok: true };
  4277. }
  4278. case 'SCHEDULE_AUTO_RUN': {
  4279. clearStopRequest();
  4280. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  4281. return await scheduleAutoRun(totalRuns, {
  4282. delayMinutes: message.payload?.delayMinutes,
  4283. autoRunSkipFailures: Boolean(message.payload?.autoRunSkipFailures),
  4284. mode: message.payload?.mode,
  4285. });
  4286. }
  4287. case 'START_SCHEDULED_AUTO_RUN_NOW': {
  4288. clearStopRequest();
  4289. const started = await launchAutoRunTimerPlan('manual', {
  4290. expectedKinds: [AUTO_RUN_TIMER_KIND_SCHEDULED_START],
  4291. });
  4292. if (!started) {
  4293. throw new Error('当前没有可立即开始的倒计时计划。');
  4294. }
  4295. return { ok: true };
  4296. }
  4297. case 'CANCEL_SCHEDULED_AUTO_RUN': {
  4298. const cancelled = await cancelScheduledAutoRun();
  4299. if (!cancelled) {
  4300. throw new Error('当前没有可取消的倒计时计划。');
  4301. }
  4302. return { ok: true };
  4303. }
  4304. case 'SKIP_AUTO_RUN_COUNTDOWN': {
  4305. clearStopRequest();
  4306. const skipped = await skipAutoRunCountdown();
  4307. if (!skipped) {
  4308. throw new Error('当前没有可立即开始的倒计时。');
  4309. }
  4310. return { ok: true };
  4311. }
  4312. case 'RESUME_AUTO_RUN': {
  4313. clearStopRequest();
  4314. if (message.payload.email) {
  4315. await setEmailState(message.payload.email);
  4316. }
  4317. resumeAutoRun().catch((error) => {
  4318. handleAutoRunLoopUnhandledError(error).catch((handlerError) => {
  4319. console.error(LOG_PREFIX, 'Failed to finalize resume error:', handlerError);
  4320. });
  4321. });
  4322. return { ok: true };
  4323. }
  4324. case 'TAKEOVER_AUTO_RUN': {
  4325. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  4326. await addLog('自动流程已切换为手动控制。', 'warn');
  4327. return { ok: true };
  4328. }
  4329. case 'SKIP_STEP': {
  4330. const step = Number(message.payload?.step);
  4331. return await skipStep(step);
  4332. }
  4333. case 'SAVE_SETTING': {
  4334. const updates = buildPersistentSettingsPayload(message.payload || {});
  4335. const sessionUpdates = buildLuckmailSessionSettingsPayload(message.payload || {});
  4336. await setPersistentSettings(updates);
  4337. await setState({
  4338. ...updates,
  4339. ...sessionUpdates,
  4340. });
  4341. return { ok: true, state: await getState() };
  4342. }
  4343. case 'EXPORT_SETTINGS': {
  4344. return { ok: true, ...(await exportSettingsBundle()) };
  4345. }
  4346. case 'IMPORT_SETTINGS': {
  4347. const state = await importSettingsBundle(message.payload?.config || null);
  4348. return { ok: true, state };
  4349. }
  4350. case 'UPSERT_HOTMAIL_ACCOUNT': {
  4351. const account = await upsertHotmailAccount(message.payload || {});
  4352. return { ok: true, account };
  4353. }
  4354. case 'DELETE_HOTMAIL_ACCOUNT': {
  4355. await deleteHotmailAccount(String(message.payload?.accountId || ''));
  4356. return { ok: true };
  4357. }
  4358. case 'DELETE_HOTMAIL_ACCOUNTS': {
  4359. const result = await deleteHotmailAccounts(String(message.payload?.mode || 'all'));
  4360. return { ok: true, ...result };
  4361. }
  4362. case 'SELECT_HOTMAIL_ACCOUNT': {
  4363. const account = await setCurrentHotmailAccount(String(message.payload?.accountId || ''), {
  4364. markUsed: false,
  4365. syncEmail: true,
  4366. });
  4367. return { ok: true, account };
  4368. }
  4369. case 'PATCH_HOTMAIL_ACCOUNT': {
  4370. const account = await patchHotmailAccount(
  4371. String(message.payload?.accountId || ''),
  4372. message.payload?.updates || {}
  4373. );
  4374. return { ok: true, account };
  4375. }
  4376. case 'VERIFY_HOTMAIL_ACCOUNT':
  4377. case 'AUTHORIZE_HOTMAIL_ACCOUNT': {
  4378. const accountId = String(message.payload?.accountId || '');
  4379. try {
  4380. const result = await verifyHotmailAccount(accountId);
  4381. await setCurrentHotmailAccount(result.account.id, { markUsed: false, syncEmail: true });
  4382. await addLog(`Hotmail 账号 ${result.account.email} 校验通过,可直接用于收信。`, 'ok');
  4383. return { ok: true, account: result.account, messageCount: result.messageCount };
  4384. } catch (err) {
  4385. const state = await getState();
  4386. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  4387. const target = findHotmailAccount(accounts, accountId);
  4388. if (target) {
  4389. target.status = 'error';
  4390. target.lastError = err.message;
  4391. await syncHotmailAccounts(accounts.map((item) => (item.id === target.id ? target : item)));
  4392. }
  4393. throw err;
  4394. }
  4395. }
  4396. case 'TEST_HOTMAIL_ACCOUNT': {
  4397. const result = await testHotmailAccountMailAccess(String(message.payload?.accountId || ''));
  4398. return { ok: true, ...result };
  4399. }
  4400. case 'LIST_LUCKMAIL_PURCHASES': {
  4401. const purchases = await listLuckmailPurchasesForManagement();
  4402. return { ok: true, purchases };
  4403. }
  4404. case 'SELECT_LUCKMAIL_PURCHASE': {
  4405. const purchase = await selectLuckmailPurchase(message.payload?.purchaseId);
  4406. return { ok: true, purchase };
  4407. }
  4408. case 'SET_LUCKMAIL_PURCHASE_USED_STATE': {
  4409. const result = await setLuckmailPurchaseUsedState(message.payload?.purchaseId, Boolean(message.payload?.used));
  4410. return { ok: true, ...result };
  4411. }
  4412. case 'SET_LUCKMAIL_PURCHASE_PRESERVED_STATE': {
  4413. const purchase = await setLuckmailPurchasePreservedState(message.payload?.purchaseId, Boolean(message.payload?.preserved));
  4414. return { ok: true, purchase };
  4415. }
  4416. case 'SET_LUCKMAIL_PURCHASE_DISABLED_STATE': {
  4417. const purchase = await setLuckmailPurchaseDisabledState(message.payload?.purchaseId, Boolean(message.payload?.disabled));
  4418. return { ok: true, purchase };
  4419. }
  4420. case 'BATCH_UPDATE_LUCKMAIL_PURCHASES': {
  4421. const result = await batchUpdateLuckmailPurchases(message.payload || {});
  4422. return { ok: true, ...result };
  4423. }
  4424. case 'DISABLE_USED_LUCKMAIL_PURCHASES': {
  4425. const result = await disableUsedLuckmailPurchases();
  4426. return { ok: true, ...result };
  4427. }
  4428. // Side panel data updates
  4429. case 'SET_EMAIL_STATE': {
  4430. const state = await getState();
  4431. if (isAutoRunLockedState(state)) {
  4432. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  4433. }
  4434. const email = String(message.payload?.email || '').trim() || null;
  4435. await setEmailStateSilently(email);
  4436. return { ok: true, email };
  4437. }
  4438. case 'SAVE_EMAIL': {
  4439. const state = await getState();
  4440. if (isAutoRunLockedState(state)) {
  4441. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  4442. }
  4443. await setEmailState(message.payload.email);
  4444. await resumeAutoRun();
  4445. return { ok: true, email: message.payload.email };
  4446. }
  4447. case 'FETCH_GENERATED_EMAIL': {
  4448. clearStopRequest();
  4449. const state = await getState();
  4450. if (isAutoRunLockedState(state)) {
  4451. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  4452. }
  4453. const email = await fetchGeneratedEmail(state, message.payload || {});
  4454. await resumeAutoRun();
  4455. return { ok: true, email };
  4456. }
  4457. case 'FETCH_DUCK_EMAIL': {
  4458. clearStopRequest();
  4459. const state = await getState();
  4460. if (isAutoRunLockedState(state)) {
  4461. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  4462. }
  4463. const email = await fetchGeneratedEmail(state, { ...(message.payload || {}), generator: 'duck' });
  4464. await resumeAutoRun();
  4465. return { ok: true, email };
  4466. }
  4467. case 'CHECK_ICLOUD_SESSION': {
  4468. clearStopRequest();
  4469. return await checkIcloudSession();
  4470. }
  4471. case 'LIST_ICLOUD_ALIASES': {
  4472. clearStopRequest();
  4473. const aliases = await listIcloudAliases();
  4474. return { ok: true, aliases };
  4475. }
  4476. case 'SET_ICLOUD_ALIAS_USED_STATE': {
  4477. clearStopRequest();
  4478. const result = await setIcloudAliasUsedState(message.payload || {});
  4479. return { ok: true, ...result };
  4480. }
  4481. case 'SET_ICLOUD_ALIAS_PRESERVED_STATE': {
  4482. clearStopRequest();
  4483. const result = await setIcloudAliasPreservedState(message.payload || {});
  4484. return { ok: true, ...result };
  4485. }
  4486. case 'DELETE_ICLOUD_ALIAS': {
  4487. clearStopRequest();
  4488. const result = await deleteIcloudAlias(message.payload || {});
  4489. return { ok: true, ...result };
  4490. }
  4491. case 'DELETE_USED_ICLOUD_ALIASES': {
  4492. clearStopRequest();
  4493. const result = await deleteUsedIcloudAliases();
  4494. return { ok: true, ...result };
  4495. }
  4496. case 'STOP_FLOW': {
  4497. await requestStop();
  4498. return { ok: true };
  4499. }
  4500. default:
  4501. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  4502. return { error: `Unknown message type: ${message.type}` };
  4503. }
  4504. }
  4505. // ============================================================
  4506. // Step Data Handlers
  4507. // ============================================================
  4508. async function handleStepData(step, payload) {
  4509. switch (step) {
  4510. case 1: {
  4511. const updates = {};
  4512. if (payload.oauthUrl) {
  4513. updates.oauthUrl = payload.oauthUrl;
  4514. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  4515. }
  4516. if (payload.sub2apiSessionId !== undefined) updates.sub2apiSessionId = payload.sub2apiSessionId || null;
  4517. if (payload.sub2apiOAuthState !== undefined) updates.sub2apiOAuthState = payload.sub2apiOAuthState || null;
  4518. if (payload.sub2apiGroupId !== undefined) updates.sub2apiGroupId = payload.sub2apiGroupId || null;
  4519. if (payload.sub2apiDraftName !== undefined) updates.sub2apiDraftName = payload.sub2apiDraftName || null;
  4520. if (Object.keys(updates).length) {
  4521. await setState(updates);
  4522. }
  4523. break;
  4524. }
  4525. case 3:
  4526. if (payload.email) await setEmailState(payload.email);
  4527. if (payload.signupVerificationRequestedAt) {
  4528. await setState({ signupVerificationRequestedAt: payload.signupVerificationRequestedAt });
  4529. }
  4530. if (payload.loginVerificationRequestedAt) {
  4531. await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt });
  4532. }
  4533. break;
  4534. case 6:
  4535. if (payload.loginVerificationRequestedAt) {
  4536. await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt });
  4537. }
  4538. break;
  4539. case 4:
  4540. await setState({
  4541. lastEmailTimestamp: payload.emailTimestamp || null,
  4542. signupVerificationRequestedAt: null,
  4543. });
  4544. break;
  4545. case 7:
  4546. await setState({
  4547. lastEmailTimestamp: payload.emailTimestamp || null,
  4548. loginVerificationRequestedAt: null,
  4549. });
  4550. break;
  4551. case 8:
  4552. if (payload.localhostUrl) {
  4553. if (!isLocalhostOAuthCallbackUrl(payload.localhostUrl)) {
  4554. throw new Error('步骤 8 返回了无效的 localhost OAuth 回调地址。');
  4555. }
  4556. await setState({ localhostUrl: payload.localhostUrl });
  4557. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  4558. }
  4559. break;
  4560. case 9: {
  4561. if (payload.localhostUrl) {
  4562. await closeLocalhostCallbackTabs(payload.localhostUrl);
  4563. }
  4564. const latestState = await getState();
  4565. if (latestState.currentHotmailAccountId && isHotmailProvider(latestState)) {
  4566. await patchHotmailAccount(latestState.currentHotmailAccountId, {
  4567. used: true,
  4568. lastUsedAt: Date.now(),
  4569. });
  4570. await addLog('当前 Hotmail 账号已自动标记为已用。', 'ok');
  4571. }
  4572. if (isLuckmailProvider(latestState)) {
  4573. const currentPurchase = getCurrentLuckmailPurchase(latestState);
  4574. if (currentPurchase?.id) {
  4575. await setLuckmailPurchaseUsedState(currentPurchase.id, true);
  4576. await addLog(`当前 LuckMail 邮箱 ${currentPurchase.email_address} 已在本地标记为已用。`, 'ok');
  4577. }
  4578. await clearLuckmailRuntimeState({ clearEmail: true });
  4579. await addLog('当前 LuckMail 邮箱运行态已清空,下轮将优先复用未用邮箱或重新购买邮箱。', 'ok');
  4580. }
  4581. const localhostPrefix = buildLocalhostCleanupPrefix(payload.localhostUrl);
  4582. if (localhostPrefix) {
  4583. await closeTabsByUrlPrefix(localhostPrefix, {
  4584. excludeUrls: [payload.localhostUrl],
  4585. excludeLocalhostCallbacks: true,
  4586. });
  4587. }
  4588. await finalizeIcloudAliasAfterSuccessfulFlow(latestState);
  4589. if (shouldUseCustomRegistrationEmail(latestState) && latestState.email) {
  4590. await setEmailStateSilently(null);
  4591. }
  4592. break;
  4593. }
  4594. }
  4595. }
  4596. // ============================================================
  4597. // Step Completion Waiting
  4598. // ============================================================
  4599. // Map of step -> { resolve, reject } for waiting on step completion
  4600. const stepWaiters = new Map();
  4601. let resumeWaiter = null;
  4602. const AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS = 120000;
  4603. const AUTO_RUN_BACKGROUND_COMPLETED_STEPS = new Set([1, 2, 4, 6, 7, 8]);
  4604. const STEP_COMPLETION_SIGNAL_STEPS = new Set([3, 5, 9]);
  4605. function waitForStepComplete(step, timeoutMs = 120000) {
  4606. return new Promise((resolve, reject) => {
  4607. throwIfStopped();
  4608. if (stepWaiters.has(step)) {
  4609. console.warn(LOG_PREFIX, `[waitForStepComplete] replacing existing waiter for step ${step}`);
  4610. }
  4611. console.log(LOG_PREFIX, `[waitForStepComplete] register step ${step}, timeout=${timeoutMs}ms`);
  4612. const timer = setTimeout(() => {
  4613. stepWaiters.delete(step);
  4614. console.warn(LOG_PREFIX, `[waitForStepComplete] timeout for step ${step} after ${timeoutMs}ms`);
  4615. reject(new Error(`步骤 ${step} 等待超时(>${timeoutMs / 1000} 秒)`));
  4616. }, timeoutMs);
  4617. stepWaiters.set(step, {
  4618. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  4619. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  4620. });
  4621. });
  4622. }
  4623. function doesStepUseCompletionSignal(step) {
  4624. return STEP_COMPLETION_SIGNAL_STEPS.has(step);
  4625. }
  4626. function notifyStepComplete(step, payload) {
  4627. const waiter = stepWaiters.get(step);
  4628. console.log(LOG_PREFIX, `[notifyStepComplete] step ${step}, hasWaiter=${Boolean(waiter)}`);
  4629. if (waiter) waiter.resolve(payload);
  4630. }
  4631. function notifyStepError(step, error) {
  4632. const waiter = stepWaiters.get(step);
  4633. console.warn(LOG_PREFIX, `[notifyStepError] step ${step}, hasWaiter=${Boolean(waiter)}, error=${error}`);
  4634. if (waiter) waiter.reject(new Error(error));
  4635. }
  4636. async function completeStepFromBackground(step, payload = {}) {
  4637. if (stopRequested) {
  4638. await setStepStatus(step, 'stopped');
  4639. notifyStepError(step, STOP_ERROR_MESSAGE);
  4640. return;
  4641. }
  4642. await setStepStatus(step, 'completed');
  4643. await addLog(`步骤 ${step} 已完成`, 'ok');
  4644. await handleStepData(step, payload);
  4645. notifyStepComplete(step, payload);
  4646. }
  4647. async function finalizeDeferredStepExecutionError(step, error) {
  4648. const latestState = await getState();
  4649. const currentStatus = latestState.stepStatuses?.[step];
  4650. if (currentStatus === 'completed' || currentStatus === 'failed' || currentStatus === 'stopped') {
  4651. return;
  4652. }
  4653. if (isStopError(error)) {
  4654. await setStepStatus(step, 'stopped');
  4655. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  4656. return;
  4657. }
  4658. await setStepStatus(step, 'failed');
  4659. await addLog(`步骤 ${step} 失败:${getErrorMessage(error)}`, 'error');
  4660. }
  4661. async function executeStepViaCompletionSignal(step, timeoutMs = AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS) {
  4662. const completionResultPromise = waitForStepComplete(step, timeoutMs).then(
  4663. payload => ({ ok: true, payload }),
  4664. error => ({ ok: false, error }),
  4665. );
  4666. let executeError = null;
  4667. try {
  4668. await executeStep(step, { deferRetryableTransportError: true });
  4669. } catch (err) {
  4670. executeError = err;
  4671. if (isStopError(err) || !isRetryableContentScriptTransportError(err)) {
  4672. notifyStepError(step, getErrorMessage(err));
  4673. }
  4674. }
  4675. const completionResult = await completionResultPromise;
  4676. if (completionResult.ok) {
  4677. if (executeError) {
  4678. console.warn(
  4679. LOG_PREFIX,
  4680. `[executeStepViaCompletionSignal] step ${step} completed after deferred execute error: ${getErrorMessage(executeError)}`
  4681. );
  4682. }
  4683. return completionResult.payload;
  4684. }
  4685. if (executeError && isRetryableContentScriptTransportError(executeError)) {
  4686. const completionMessage = getErrorMessage(completionResult.error);
  4687. if (/等待超时/.test(completionMessage)) {
  4688. await finalizeDeferredStepExecutionError(step, executeError);
  4689. throw executeError;
  4690. }
  4691. throw completionResult.error;
  4692. }
  4693. if (executeError) {
  4694. throw executeError;
  4695. }
  4696. throw completionResult.error;
  4697. }
  4698. async function waitForRunningStepsToFinish(payload = {}) {
  4699. let currentState = await getState();
  4700. let runningSteps = getRunningSteps(currentState.stepStatuses);
  4701. if (!runningSteps.length) {
  4702. return currentState;
  4703. }
  4704. await addLog(`自动继续:检测到步骤 ${runningSteps.join(', ')} 正在运行,等待完成后再继续自动流程...`, 'info');
  4705. await broadcastAutoRunStatus('waiting_step', payload);
  4706. while (runningSteps.length) {
  4707. await sleepWithStop(250);
  4708. currentState = await getState();
  4709. runningSteps = getRunningSteps(currentState.stepStatuses);
  4710. }
  4711. await addLog('自动继续:当前运行步骤已结束,准备按最新进度继续自动流程...', 'info');
  4712. return currentState;
  4713. }
  4714. async function markRunningStepsStopped() {
  4715. const state = await getState();
  4716. const runningSteps = getRunningSteps(state.stepStatuses);
  4717. for (const step of runningSteps) {
  4718. await setStepStatus(step, 'stopped');
  4719. }
  4720. }
  4721. async function requestStop(options = {}) {
  4722. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  4723. const state = await getState();
  4724. const timerPlan = getPendingAutoRunTimerPlan(state);
  4725. if (timerPlan?.kind === AUTO_RUN_TIMER_KIND_SCHEDULED_START && !autoRunActive) {
  4726. await cancelScheduledAutoRun({
  4727. logMessage: options.logMessage === false
  4728. ? false
  4729. : (options.logMessage || '已取消自动运行倒计时计划。'),
  4730. });
  4731. return;
  4732. }
  4733. if (timerPlan && !autoRunActive) {
  4734. autoRunCurrentRun = timerPlan.currentRun;
  4735. autoRunTotalRuns = timerPlan.totalRuns;
  4736. autoRunAttemptRun = timerPlan.attemptRun;
  4737. if (options.logMessage !== false) {
  4738. await addLog(options.logMessage || '已停止等待中的自动流程。', 'warn');
  4739. }
  4740. await broadcastAutoRunStatus('stopped', {
  4741. currentRun: timerPlan.currentRun,
  4742. totalRuns: timerPlan.totalRuns,
  4743. attemptRun: timerPlan.attemptRun,
  4744. }, {
  4745. autoRunSkipFailures: timerPlan.autoRunSkipFailures,
  4746. autoRunRoundSummaries: serializeAutoRunRoundSummaries(timerPlan.totalRuns, timerPlan.roundSummaries),
  4747. autoRunTimerPlan: null,
  4748. scheduledAutoRunPlan: null,
  4749. });
  4750. await clearAutoRunTimerAlarm();
  4751. clearStopRequest();
  4752. return;
  4753. }
  4754. if (stopRequested) return;
  4755. stopRequested = true;
  4756. cancelPendingCommands();
  4757. cleanupStep8NavigationListeners();
  4758. rejectPendingStep8(new Error(STOP_ERROR_MESSAGE));
  4759. await addLog(logMessage, 'warn');
  4760. await broadcastStopToContentScripts();
  4761. for (const waiter of stepWaiters.values()) {
  4762. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  4763. }
  4764. stepWaiters.clear();
  4765. if (resumeWaiter) {
  4766. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  4767. resumeWaiter = null;
  4768. }
  4769. await markRunningStepsStopped();
  4770. autoRunActive = false;
  4771. await broadcastAutoRunStatus('stopped', {
  4772. currentRun: autoRunCurrentRun,
  4773. totalRuns: autoRunTotalRuns,
  4774. attemptRun: autoRunAttemptRun,
  4775. }, {
  4776. autoRunTimerPlan: null,
  4777. scheduledAutoRunPlan: null,
  4778. });
  4779. }
  4780. // ============================================================
  4781. // Step Execution
  4782. // ============================================================
  4783. async function executeStep(step, options = {}) {
  4784. const { deferRetryableTransportError = false } = options;
  4785. console.log(LOG_PREFIX, `Executing step ${step}`);
  4786. throwIfStopped();
  4787. await setStepStatus(step, 'running');
  4788. await addLog(`步骤 ${step} 开始执行`);
  4789. await humanStepDelay();
  4790. const state = await getState();
  4791. // Set flow start time on first step
  4792. if (step === 1 && !state.flowStartTime) {
  4793. await setState({ flowStartTime: Date.now() });
  4794. }
  4795. try {
  4796. switch (step) {
  4797. case 1: await executeStep1(state); break;
  4798. case 2: await executeStep2(state); break;
  4799. case 3: await executeStep3(state); break;
  4800. case 4: await executeStep4(state); break;
  4801. case 5: await executeStep5(state); break;
  4802. case 6: await executeStep6(state); break;
  4803. case 7: await executeStep7(state); break;
  4804. case 8: await executeStep8(state); break;
  4805. case 9: await executeStep9(state); break;
  4806. default:
  4807. throw new Error(`未知步骤:${step}`);
  4808. }
  4809. } catch (err) {
  4810. if (isStopError(err)) {
  4811. await setStepStatus(step, 'stopped');
  4812. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  4813. throw err;
  4814. }
  4815. if (!(deferRetryableTransportError && doesStepUseCompletionSignal(step) && isRetryableContentScriptTransportError(err))) {
  4816. await setStepStatus(step, 'failed');
  4817. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  4818. } else {
  4819. console.warn(
  4820. LOG_PREFIX,
  4821. `[executeStep] deferring retryable transport error for step ${step}: ${getErrorMessage(err)}`
  4822. );
  4823. }
  4824. throw err;
  4825. }
  4826. }
  4827. /**
  4828. * Execute a step and wait for it to complete before returning.
  4829. * @param {number} step
  4830. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  4831. */
  4832. async function executeStepAndWait(step, delayAfter = 2000) {
  4833. throwIfStopped();
  4834. const delaySeconds = normalizeAutoStepDelaySeconds((await getState()).autoStepDelaySeconds, null);
  4835. if (delaySeconds > 0) {
  4836. await addLog(
  4837. `自动运行:步骤 ${step} 执行前额外等待 ${delaySeconds} 秒,避免节奏过快。`,
  4838. 'info'
  4839. );
  4840. await sleepWithStop(delaySeconds * 1000);
  4841. }
  4842. if (AUTO_RUN_BACKGROUND_COMPLETED_STEPS.has(step)) {
  4843. await addLog(`自动运行:步骤 ${step} 由后台流程负责收尾,执行函数返回后将直接进入下一步。`, 'info');
  4844. await executeStep(step);
  4845. const latestState = await getState();
  4846. await addLog(`自动运行:步骤 ${step} 已执行返回,当前状态为 ${latestState.stepStatuses?.[step] || 'pending'},准备继续后续步骤。`, 'info');
  4847. } else if (doesStepUseCompletionSignal(step)) {
  4848. await addLog(`自动运行:步骤 ${step} 已发起,正在等待完成信号(超时 ${AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS / 1000} 秒)。`, 'info');
  4849. await executeStepViaCompletionSignal(step, AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS);
  4850. await addLog(`自动运行:步骤 ${step} 已收到完成信号,准备继续后续步骤。`, 'info');
  4851. } else {
  4852. await executeStep(step);
  4853. }
  4854. // Extra delay for page transitions / DOM updates
  4855. if (delayAfter > 0) {
  4856. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  4857. }
  4858. }
  4859. function getEmailGeneratorLabel(generator) {
  4860. if (generator === 'custom') {
  4861. return '自定义邮箱';
  4862. }
  4863. if (generator === 'icloud') {
  4864. return 'iCloud 隐私邮箱';
  4865. }
  4866. if (generator === 'cloudflare') return 'Cloudflare 邮箱';
  4867. if (generator === CLOUDFLARE_TEMP_EMAIL_GENERATOR) return 'Cloudflare Temp Email';
  4868. return 'Duck 邮箱';
  4869. }
  4870. function generateCloudflareAliasLocalPart() {
  4871. const letters = 'abcdefghijklmnopqrstuvwxyz';
  4872. const digits = '0123456789';
  4873. const chars = [];
  4874. for (let i = 0; i < 6; i++) {
  4875. chars.push(letters[Math.floor(Math.random() * letters.length)]);
  4876. }
  4877. for (let i = 0; i < 4; i++) {
  4878. chars.push(digits[Math.floor(Math.random() * digits.length)]);
  4879. }
  4880. for (let i = chars.length - 1; i > 0; i--) {
  4881. const j = Math.floor(Math.random() * (i + 1));
  4882. [chars[i], chars[j]] = [chars[j], chars[i]];
  4883. }
  4884. return chars.join('');
  4885. }
  4886. async function fetchCloudflareEmail(state, options = {}) {
  4887. throwIfStopped();
  4888. const latestState = state || await getState();
  4889. const domain = normalizeCloudflareDomain(latestState.cloudflareDomain);
  4890. if (!domain) {
  4891. throw new Error('Cloudflare 域名为空或格式无效。');
  4892. }
  4893. const localPart = String(options.localPart || '').trim().toLowerCase() || generateCloudflareAliasLocalPart();
  4894. const aliasEmail = `${localPart}@${domain}`;
  4895. await setEmailState(aliasEmail);
  4896. await addLog(`Cloudflare 邮箱:已生成 ${aliasEmail}`, 'ok');
  4897. return aliasEmail;
  4898. }
  4899. function ensureCloudflareTempEmailConfig(state, options = {}) {
  4900. const {
  4901. requireAdminAuth = false,
  4902. requireDomain = false,
  4903. } = options;
  4904. const config = getCloudflareTempEmailConfig(state);
  4905. if (!config.baseUrl) {
  4906. throw new Error('Cloudflare Temp Email 服务地址为空或格式无效。');
  4907. }
  4908. if (requireAdminAuth && !config.adminAuth) {
  4909. throw new Error('Cloudflare Temp Email 缺少 Admin Auth。');
  4910. }
  4911. if (requireDomain && !config.domain) {
  4912. throw new Error('Cloudflare Temp Email 域名为空或格式无效。');
  4913. }
  4914. return config;
  4915. }
  4916. async function requestCloudflareTempEmailJson(config, path, options = {}) {
  4917. const {
  4918. method = 'GET',
  4919. payload,
  4920. searchParams,
  4921. timeoutMs = 20000,
  4922. } = options;
  4923. const url = new URL(joinCloudflareTempEmailUrl(config.baseUrl, path));
  4924. if (searchParams && typeof searchParams === 'object') {
  4925. for (const [key, value] of Object.entries(searchParams)) {
  4926. if (value === undefined || value === null || value === '') continue;
  4927. url.searchParams.set(key, String(value));
  4928. }
  4929. }
  4930. const controller = new AbortController();
  4931. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
  4932. let response;
  4933. try {
  4934. response = await fetch(url.toString(), {
  4935. method,
  4936. headers: buildCloudflareTempEmailHeaders(config, {
  4937. json: payload !== undefined,
  4938. }),
  4939. body: payload !== undefined ? JSON.stringify(payload) : undefined,
  4940. signal: controller.signal,
  4941. });
  4942. } catch (err) {
  4943. const errorMessage = err?.name === 'AbortError'
  4944. ? `Cloudflare Temp Email 请求超时(>${Math.round(timeoutMs / 1000)} 秒)`
  4945. : `Cloudflare Temp Email 请求失败:${err.message}`;
  4946. throw new Error(errorMessage);
  4947. } finally {
  4948. clearTimeout(timeoutId);
  4949. }
  4950. const text = await response.text();
  4951. let parsed;
  4952. try {
  4953. parsed = text ? JSON.parse(text) : {};
  4954. } catch {
  4955. parsed = text;
  4956. }
  4957. if (!response.ok) {
  4958. const payloadError = typeof parsed === 'object' && parsed
  4959. ? (parsed.message || parsed.error || parsed.msg)
  4960. : '';
  4961. throw new Error(`Cloudflare Temp Email 请求失败:${payloadError || text || `HTTP ${response.status}`}`);
  4962. }
  4963. return parsed;
  4964. }
  4965. async function fetchCloudflareTempEmailAddress(state, options = {}) {
  4966. throwIfStopped();
  4967. const latestState = state || await getState();
  4968. const config = ensureCloudflareTempEmailConfig(latestState, {
  4969. requireAdminAuth: true,
  4970. requireDomain: true,
  4971. });
  4972. const requestedName = String(options.localPart || options.name || '').trim().toLowerCase() || generateCloudflareAliasLocalPart();
  4973. const payload = {
  4974. enablePrefix: true,
  4975. name: requestedName,
  4976. domain: config.domain,
  4977. };
  4978. const result = await requestCloudflareTempEmailJson(config, '/admin/new_address', {
  4979. method: 'POST',
  4980. payload,
  4981. });
  4982. const address = normalizeCloudflareTempEmailAddress(getCloudflareTempEmailAddressFromResponse(result));
  4983. if (!address) {
  4984. throw new Error('Cloudflare Temp Email 未返回可用邮箱地址。');
  4985. }
  4986. await setEmailState(address);
  4987. await addLog(`Cloudflare Temp Email:已生成 ${address}`, 'ok');
  4988. return address;
  4989. }
  4990. async function fetchDuckEmail(options = {}) {
  4991. throwIfStopped();
  4992. const { generateNew = true } = options;
  4993. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  4994. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  4995. const result = await sendToContentScript('duck-mail', {
  4996. type: 'FETCH_DUCK_EMAIL',
  4997. source: 'background',
  4998. payload: { generateNew },
  4999. });
  5000. if (result?.error) {
  5001. throw new Error(result.error);
  5002. }
  5003. if (!result?.email) {
  5004. throw new Error('未返回 Duck 邮箱地址。');
  5005. }
  5006. await setEmailState(result.email);
  5007. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  5008. return result.email;
  5009. }
  5010. async function fetchGeneratedEmail(state, options = {}) {
  5011. const currentState = state || await getState();
  5012. const generator = normalizeEmailGenerator(options.generator ?? currentState.emailGenerator);
  5013. if (generator === 'custom') {
  5014. throw new Error('当前邮箱生成方式为自定义邮箱,请直接填写注册邮箱。');
  5015. }
  5016. if (generator === 'icloud') {
  5017. return fetchIcloudHideMyEmail();
  5018. }
  5019. if (generator === 'cloudflare') {
  5020. return fetchCloudflareEmail(currentState, options);
  5021. }
  5022. if (generator === CLOUDFLARE_TEMP_EMAIL_GENERATOR) {
  5023. return fetchCloudflareTempEmailAddress(currentState, options);
  5024. }
  5025. return fetchDuckEmail(options);
  5026. }
  5027. // ============================================================
  5028. // Auto Run Flow
  5029. // ============================================================
  5030. let autoRunActive = false;
  5031. let autoRunCurrentRun = 0;
  5032. let autoRunTotalRuns = 1;
  5033. let autoRunAttemptRun = 0;
  5034. const EMAIL_FETCH_MAX_ATTEMPTS = 5;
  5035. const VERIFICATION_POLL_MAX_ROUNDS = 5;
  5036. const STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS = 25000;
  5037. const AUTO_STEP_DELAYS = {
  5038. 1: 2000,
  5039. 2: 2000,
  5040. 3: 3000,
  5041. 4: 2000,
  5042. 5: 3000,
  5043. 6: 3000,
  5044. 7: 2000,
  5045. 8: 2000,
  5046. 9: 1000,
  5047. };
  5048. async function resumeAutoRunIfWaitingForEmail(options = {}) {
  5049. const { silent = false } = options;
  5050. const state = await getState();
  5051. if (!state.email || !isAutoRunPausedState(state)) {
  5052. return false;
  5053. }
  5054. if (resumeWaiter) {
  5055. if (!silent) {
  5056. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  5057. }
  5058. resumeWaiter.resolve();
  5059. resumeWaiter = null;
  5060. return true;
  5061. }
  5062. return false;
  5063. }
  5064. async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
  5065. const currentState = await getState();
  5066. if (isHotmailProvider(currentState)) {
  5067. const account = await ensureHotmailAccountForFlow({
  5068. allowAllocate: true,
  5069. markUsed: true,
  5070. preferredAccountId: null,
  5071. });
  5072. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:已分配 Hotmail 账号 ${account.email}(第 ${attemptRuns} 次尝试)===`, 'ok');
  5073. return account.email;
  5074. }
  5075. if (isLuckmailProvider(currentState)) {
  5076. const purchase = await ensureLuckmailPurchaseForFlow({ allowReuse: true });
  5077. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:LuckMail 邮箱已就绪:${purchase.email_address}(第 ${attemptRuns} 次尝试)===`, 'ok');
  5078. return purchase.email_address;
  5079. }
  5080. if (isGeneratedAliasProvider(currentState)) {
  5081. if (currentState.mailProvider === GMAIL_PROVIDER) {
  5082. if (!currentState.emailPrefix) {
  5083. throw new Error('Gmail 原邮箱未设置,请先在侧边栏填写。');
  5084. }
  5085. await addLog(`=== 鐩爣 ${targetRun}/${totalRuns} 杞細Gmail +tag 妯″紡宸插惎鐢紝灏嗗湪姝ラ 3 鑷姩鐢熸垚閭锛堢 ${attemptRuns} 娆″皾璇曪級===`, 'info');
  5086. return null;
  5087. }
  5088. if (!currentState.emailPrefix) {
  5089. throw new Error('2925 邮箱前缀未设置,请先在侧边栏填写。');
  5090. }
  5091. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:2925 模式已启用,将在步骤 3 自动生成邮箱(第 ${attemptRuns} 次尝试)===`, 'info');
  5092. return null;
  5093. }
  5094. if (currentState.email) {
  5095. return currentState.email;
  5096. }
  5097. if (shouldUseCustomRegistrationEmail(currentState)) {
  5098. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先填写自定义注册邮箱,然后继续 ===`, 'warn');
  5099. await broadcastAutoRunStatus('waiting_email', {
  5100. currentRun: targetRun,
  5101. totalRuns,
  5102. attemptRun: attemptRuns,
  5103. });
  5104. await waitForResume();
  5105. const resumedState = await getState();
  5106. if (!resumedState.email) {
  5107. throw new Error('无法继续:当前没有注册邮箱。');
  5108. }
  5109. return resumedState.email;
  5110. }
  5111. const generator = normalizeEmailGenerator(currentState.emailGenerator);
  5112. const generatorLabel = getEmailGeneratorLabel(generator);
  5113. let lastError = null;
  5114. for (let attempt = 1; attempt <= EMAIL_FETCH_MAX_ATTEMPTS; attempt++) {
  5115. try {
  5116. if (attempt > 1) {
  5117. await addLog(`${generatorLabel}:正在进行第 ${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS} 次自动获取重试...`, 'warn');
  5118. }
  5119. const generatedEmail = await fetchGeneratedEmail(currentState, { generateNew: true, generator });
  5120. await addLog(
  5121. `=== 目标 ${targetRun}/${totalRuns} 轮:${generatorLabel}已就绪:${generatedEmail}(第 ${attemptRuns} 次尝试,第 ${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS} 次获取)===`,
  5122. 'ok'
  5123. );
  5124. return generatedEmail;
  5125. } catch (err) {
  5126. lastError = err;
  5127. await addLog(`${generatorLabel}自动获取失败(${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS}):${err.message}`, 'warn');
  5128. if (
  5129. (generator === 'cloudflare' && /域名/.test(String(err.message || '')))
  5130. || (generator === CLOUDFLARE_TEMP_EMAIL_GENERATOR && /(服务地址|Admin Auth|域名)/.test(String(err.message || '')))
  5131. ) {
  5132. break;
  5133. }
  5134. }
  5135. }
  5136. await addLog(`${generatorLabel}自动获取已连续失败 ${EMAIL_FETCH_MAX_ATTEMPTS} 次:${lastError?.message || '未知错误'}`, 'error');
  5137. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先自动获取邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  5138. await broadcastAutoRunStatus('waiting_email', {
  5139. currentRun: targetRun,
  5140. totalRuns,
  5141. attemptRun: attemptRuns,
  5142. });
  5143. await waitForResume();
  5144. const resumedState = await getState();
  5145. if (!resumedState.email) {
  5146. throw new Error('无法继续:当前没有邮箱地址。');
  5147. }
  5148. return resumedState.email;
  5149. }
  5150. async function runAutoSequenceFromStep(startStep, context = {}) {
  5151. const { targetRun, totalRuns, attemptRuns, continued = false } = context;
  5152. const maxStep9RestartAttempts = 5;
  5153. let step9RestartAttempts = 0;
  5154. if (continued) {
  5155. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续当前进度,从步骤 ${startStep} 开始(第 ${attemptRuns} 次尝试)===`, 'info');
  5156. } else {
  5157. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,打开官网并进入密码页 ===`, 'info');
  5158. }
  5159. if (startStep <= 1) {
  5160. await executeStepAndWait(1, AUTO_STEP_DELAYS[1]);
  5161. }
  5162. if (startStep <= 2) {
  5163. await ensureAutoEmailReady(targetRun, totalRuns, attemptRuns);
  5164. await executeStepAndWait(2, AUTO_STEP_DELAYS[2]);
  5165. }
  5166. if (startStep <= 3) {
  5167. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,填写密码、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  5168. await broadcastAutoRunStatus('running', {
  5169. currentRun: targetRun,
  5170. totalRuns,
  5171. attemptRun: attemptRuns,
  5172. });
  5173. await executeStepAndWait(3, AUTO_STEP_DELAYS[3]);
  5174. } else {
  5175. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续执行剩余流程(第 ${attemptRuns} 次尝试)===`, 'info');
  5176. }
  5177. const signupTabId = await getTabId('signup-page');
  5178. if (signupTabId) {
  5179. await chrome.tabs.update(signupTabId, { active: true });
  5180. }
  5181. let step = Math.max(startStep, 4);
  5182. while (step <= 9) {
  5183. try {
  5184. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  5185. const latestState = await getState();
  5186. if (step === 6 && shouldSkipLoginVerificationForCpaCallback(latestState)) {
  5187. step = 8;
  5188. continue;
  5189. }
  5190. step += 1;
  5191. } catch (err) {
  5192. const latestState = await getState();
  5193. const currentMail = getMailConfig(latestState);
  5194. const shouldRetryStep9 = step === 9
  5195. && (
  5196. isLegacyStep9RecoverableAuthError(err)
  5197. || (currentMail.provider === HOTMAIL_PROVIDER && isStep9RecoverableAuthError(err))
  5198. )
  5199. && step9RestartAttempts < maxStep9RestartAttempts;
  5200. if (shouldRetryStep9) {
  5201. step9RestartAttempts += 1;
  5202. await addLog(
  5203. `步骤 9:检测到 CPA 认证失败,正在回到步骤 6 重新开始授权流程(${step9RestartAttempts}/${maxStep9RestartAttempts})...`,
  5204. 'warn'
  5205. );
  5206. await invalidateDownstreamAfterStepRestart(6, {
  5207. logLabel: `步骤 9 认证失败后准备回到步骤 6 重试(${step9RestartAttempts}/${maxStep9RestartAttempts})`,
  5208. });
  5209. step = 6;
  5210. continue;
  5211. }
  5212. throw err;
  5213. }
  5214. }
  5215. }
  5216. async function waitForResume() {
  5217. throwIfStopped();
  5218. const state = await getState();
  5219. if (state.email) {
  5220. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  5221. return;
  5222. }
  5223. return new Promise((resolve, reject) => {
  5224. resumeWaiter = { resolve, reject };
  5225. });
  5226. }
  5227. function createAutoRunRoundSummary(round) {
  5228. return {
  5229. round,
  5230. status: 'pending',
  5231. attempts: 0,
  5232. failureReasons: [],
  5233. finalFailureReason: '',
  5234. };
  5235. }
  5236. function normalizeAutoRunRoundSummary(summary, round) {
  5237. const base = createAutoRunRoundSummary(round);
  5238. if (!summary || typeof summary !== 'object') {
  5239. return base;
  5240. }
  5241. const status = String(summary.status || '').trim().toLowerCase();
  5242. return {
  5243. round,
  5244. status: ['pending', 'success', 'failed'].includes(status) ? status : base.status,
  5245. attempts: Math.max(0, Math.floor(Number(summary.attempts) || 0)),
  5246. failureReasons: Array.isArray(summary.failureReasons)
  5247. ? summary.failureReasons.map((item) => String(item || '').trim()).filter(Boolean)
  5248. : [],
  5249. finalFailureReason: String(summary.finalFailureReason || '').trim(),
  5250. };
  5251. }
  5252. function buildAutoRunRoundSummaries(totalRuns, rawSummaries = []) {
  5253. return Array.from({ length: totalRuns }, (_, index) => {
  5254. return normalizeAutoRunRoundSummary(rawSummaries[index], index + 1);
  5255. });
  5256. }
  5257. function serializeAutoRunRoundSummaries(totalRuns, roundSummaries = []) {
  5258. return buildAutoRunRoundSummaries(totalRuns, roundSummaries).map((summary) => ({
  5259. ...summary,
  5260. failureReasons: [...summary.failureReasons],
  5261. }));
  5262. }
  5263. function getAutoRunRoundRetryCount(summary) {
  5264. return Math.max(0, Number(summary?.attempts || 0) - 1);
  5265. }
  5266. function formatAutoRunFailureReasons(reasons = []) {
  5267. if (!Array.isArray(reasons) || !reasons.length) {
  5268. return '未知错误';
  5269. }
  5270. const counts = new Map();
  5271. for (const reason of reasons) {
  5272. const normalized = String(reason || '').trim() || '未知错误';
  5273. counts.set(normalized, (counts.get(normalized) || 0) + 1);
  5274. }
  5275. return Array.from(counts.entries())
  5276. .map(([reason, count]) => (count > 1 ? `${reason}(${count}次)` : reason))
  5277. .join(';');
  5278. }
  5279. async function logAutoRunFinalSummary(totalRuns, roundSummaries = []) {
  5280. const summaries = buildAutoRunRoundSummaries(totalRuns, roundSummaries);
  5281. const successRounds = summaries.filter((item) => item.status === 'success');
  5282. const failedRounds = summaries.filter((item) => item.status === 'failed');
  5283. const pendingRounds = summaries.filter((item) => item.status === 'pending');
  5284. await addLog('=== 自动运行汇总 ===', failedRounds.length ? 'warn' : 'ok');
  5285. await addLog(
  5286. `总轮数:${totalRuns};成功:${successRounds.length};失败:${failedRounds.length};未完成:${pendingRounds.length}`,
  5287. failedRounds.length ? 'warn' : 'ok'
  5288. );
  5289. if (successRounds.length) {
  5290. await addLog(
  5291. `成功轮次:${successRounds
  5292. .map((item) => `第 ${item.round} 轮(重试 ${getAutoRunRoundRetryCount(item)} 次)`)
  5293. .join(';')}`,
  5294. 'ok'
  5295. );
  5296. }
  5297. if (failedRounds.length) {
  5298. await addLog(
  5299. `失败轮次:${failedRounds
  5300. .map((item) => {
  5301. const retryCount = getAutoRunRoundRetryCount(item);
  5302. const finalReason = item.finalFailureReason || item.failureReasons[item.failureReasons.length - 1] || '未知错误';
  5303. const reasonSummary = formatAutoRunFailureReasons(item.failureReasons);
  5304. return `第 ${item.round} 轮(重试 ${retryCount} 次,最终原因:${finalReason};失败记录:${reasonSummary})`;
  5305. })
  5306. .join(';')}`,
  5307. 'error'
  5308. );
  5309. }
  5310. if (pendingRounds.length) {
  5311. await addLog(
  5312. `未完成轮次:${pendingRounds.map((item) => `第 ${item.round} 轮`).join(';')}`,
  5313. 'warn'
  5314. );
  5315. }
  5316. }
  5317. async function skipAutoRunCountdown() {
  5318. const state = await getState();
  5319. const plan = getPendingAutoRunTimerPlan(state);
  5320. if (!plan || state.autoRunPhase !== 'waiting_interval') {
  5321. return false;
  5322. }
  5323. return launchAutoRunTimerPlan('manual', {
  5324. expectedKinds: [
  5325. AUTO_RUN_TIMER_KIND_BETWEEN_ROUNDS,
  5326. AUTO_RUN_TIMER_KIND_BEFORE_RETRY,
  5327. ],
  5328. });
  5329. }
  5330. async function waitBetweenAutoRunRounds(targetRun, totalRuns, roundSummary, options = {}) {
  5331. const { autoRunSkipFailures = false, roundSummaries = [] } = options;
  5332. if (totalRuns <= 1 || targetRun >= totalRuns) {
  5333. return false;
  5334. }
  5335. const fallbackThreadIntervalMinutes = normalizeAutoRunFallbackThreadIntervalMinutes(
  5336. (await getState()).autoRunFallbackThreadIntervalMinutes
  5337. );
  5338. if (fallbackThreadIntervalMinutes <= 0) {
  5339. return false;
  5340. }
  5341. const statusLabel = roundSummary?.status === 'failed' ? '失败' : '完成';
  5342. await addLog(
  5343. `线程间隔:第 ${targetRun}/${totalRuns} 轮已${statusLabel},等待 ${fallbackThreadIntervalMinutes} 分钟后开始下一轮。`,
  5344. 'info'
  5345. );
  5346. await persistAutoRunTimerPlan({
  5347. kind: AUTO_RUN_TIMER_KIND_BETWEEN_ROUNDS,
  5348. fireAt: Date.now() + fallbackThreadIntervalMinutes * 60 * 1000,
  5349. currentRun: targetRun,
  5350. totalRuns,
  5351. attemptRun: autoRunAttemptRun,
  5352. autoRunSkipFailures,
  5353. roundSummaries,
  5354. countdownTitle: '线程间隔中',
  5355. countdownNote: `第 ${Math.min(targetRun + 1, totalRuns)}/${totalRuns} 轮即将开始`,
  5356. }, {
  5357. autoRunSkipFailures,
  5358. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  5359. });
  5360. autoRunActive = false;
  5361. return true;
  5362. }
  5363. async function waitBeforeAutoRunRetry(targetRun, totalRuns, nextAttemptRun, options = {}) {
  5364. const { autoRunSkipFailures = false, roundSummaries = [] } = options;
  5365. const fallbackThreadIntervalMinutes = normalizeAutoRunFallbackThreadIntervalMinutes(
  5366. (await getState()).autoRunFallbackThreadIntervalMinutes
  5367. );
  5368. if (fallbackThreadIntervalMinutes <= 0) {
  5369. return false;
  5370. }
  5371. await addLog(
  5372. `线程间隔:等待 ${fallbackThreadIntervalMinutes} 分钟后开始第 ${targetRun}/${totalRuns} 轮第 ${nextAttemptRun} 次尝试。`,
  5373. 'info'
  5374. );
  5375. await persistAutoRunTimerPlan({
  5376. kind: AUTO_RUN_TIMER_KIND_BEFORE_RETRY,
  5377. fireAt: Date.now() + fallbackThreadIntervalMinutes * 60 * 1000,
  5378. currentRun: targetRun,
  5379. totalRuns,
  5380. attemptRun: nextAttemptRun,
  5381. autoRunSkipFailures,
  5382. roundSummaries,
  5383. countdownTitle: '线程间隔中',
  5384. countdownNote: `第 ${targetRun}/${totalRuns} 轮第 ${nextAttemptRun} 次尝试即将开始`,
  5385. }, {
  5386. autoRunSkipFailures,
  5387. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  5388. });
  5389. autoRunActive = false;
  5390. return true;
  5391. }
  5392. async function handleAutoRunLoopUnhandledError(error) {
  5393. console.error(LOG_PREFIX, 'Auto run loop crashed:', error);
  5394. if (!isStopError(error)) {
  5395. await addLog(`自动运行异常终止:${getErrorMessage(error) || '未知错误'}`, 'error');
  5396. }
  5397. autoRunActive = false;
  5398. await broadcastAutoRunStatus('stopped', {
  5399. currentRun: autoRunCurrentRun,
  5400. totalRuns: autoRunTotalRuns,
  5401. attemptRun: autoRunAttemptRun,
  5402. }, {
  5403. autoRunTimerPlan: null,
  5404. scheduledAutoRunPlan: null,
  5405. });
  5406. clearStopRequest();
  5407. }
  5408. function startAutoRunLoop(totalRuns, options = {}) {
  5409. autoRunLoop(totalRuns, options).catch((error) => {
  5410. handleAutoRunLoopUnhandledError(error).catch((handlerError) => {
  5411. console.error(LOG_PREFIX, 'Failed to finalize auto run error:', handlerError);
  5412. });
  5413. });
  5414. }
  5415. async function autoRunLoop(totalRuns, options = {}) {
  5416. if (autoRunActive) {
  5417. await addLog('自动运行已在进行中', 'warn');
  5418. return;
  5419. }
  5420. clearStopRequest();
  5421. autoRunActive = true;
  5422. autoRunTotalRuns = totalRuns;
  5423. autoRunCurrentRun = 0;
  5424. autoRunAttemptRun = 0;
  5425. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  5426. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  5427. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) && options.resumeCurrentRun > 0
  5428. ? Math.min(totalRuns, options.resumeCurrentRun)
  5429. : 1;
  5430. const resumeAttemptRun = Number.isInteger(options.resumeAttemptRun) && options.resumeAttemptRun > 0
  5431. ? Math.min(AUTO_RUN_MAX_RETRIES_PER_ROUND + 1, options.resumeAttemptRun)
  5432. : 1;
  5433. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  5434. let forceFreshTabsNextRun = false;
  5435. let stoppedEarly = false;
  5436. let parkedByTimer = false;
  5437. const roundSummaries = buildAutoRunRoundSummaries(totalRuns, options.resumeRoundSummaries);
  5438. if (continueCurrentOnFirstAttempt && resumeCurrentRun > 1) {
  5439. for (let round = 1; round < resumeCurrentRun; round += 1) {
  5440. const summary = roundSummaries[round - 1];
  5441. if (summary.status === 'pending') {
  5442. summary.status = 'success';
  5443. if (!summary.attempts) {
  5444. summary.attempts = 1;
  5445. }
  5446. }
  5447. }
  5448. }
  5449. let successfulRuns = roundSummaries.filter((item) => item.status === 'success').length;
  5450. const initialState = await getState();
  5451. const initialPhase = continueCurrentOnFirstAttempt && getRunningSteps(initialState.stepStatuses).length
  5452. ? 'waiting_step'
  5453. : 'running';
  5454. const showResumePosition = continueCurrentOnFirstAttempt || resumeCurrentRun > 1 || resumeAttemptRun > 1;
  5455. await setState({
  5456. autoRunSkipFailures,
  5457. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  5458. ...getAutoRunStatusPayload(initialPhase, {
  5459. currentRun: showResumePosition ? resumeCurrentRun : 0,
  5460. totalRuns,
  5461. attemptRun: showResumePosition ? resumeAttemptRun : 0,
  5462. }),
  5463. });
  5464. for (let targetRun = resumeCurrentRun; targetRun <= totalRuns; targetRun += 1) {
  5465. const roundSummary = roundSummaries[targetRun - 1];
  5466. const resumingCurrentRound = continueCurrentOnFirstAttempt && targetRun === resumeCurrentRun;
  5467. let attemptRun = resumingCurrentRound ? resumeAttemptRun : 1;
  5468. let reuseExistingProgress = resumingCurrentRound;
  5469. const maxAttemptsForRound = autoRunSkipFailures
  5470. ? AUTO_RUN_MAX_RETRIES_PER_ROUND + 1
  5471. : Math.max(1, attemptRun);
  5472. while (attemptRun <= maxAttemptsForRound) {
  5473. autoRunCurrentRun = targetRun;
  5474. autoRunAttemptRun = attemptRun;
  5475. roundSummary.attempts = attemptRun;
  5476. let startStep = 1;
  5477. let useExistingProgress = false;
  5478. if (reuseExistingProgress) {
  5479. let currentState = await getState();
  5480. if (getRunningSteps(currentState.stepStatuses).length) {
  5481. currentState = await waitForRunningStepsToFinish({
  5482. currentRun: targetRun,
  5483. totalRuns,
  5484. attemptRun,
  5485. });
  5486. }
  5487. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  5488. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  5489. startStep = resumeStep;
  5490. useExistingProgress = true;
  5491. } else if (hasSavedProgress(currentState.stepStatuses)) {
  5492. await addLog('检测到当前流程已处理完成,本轮将改为从步骤 1 重新开始。', 'info');
  5493. }
  5494. }
  5495. if (!useExistingProgress) {
  5496. const prevState = await getState();
  5497. const keepSettings = {
  5498. vpsUrl: prevState.vpsUrl,
  5499. vpsPassword: prevState.vpsPassword,
  5500. customPassword: prevState.customPassword,
  5501. autoRunSkipFailures: prevState.autoRunSkipFailures,
  5502. autoRunFallbackThreadIntervalMinutes: prevState.autoRunFallbackThreadIntervalMinutes,
  5503. autoRunDelayEnabled: prevState.autoRunDelayEnabled,
  5504. autoRunDelayMinutes: prevState.autoRunDelayMinutes,
  5505. autoStepDelaySeconds: prevState.autoStepDelaySeconds,
  5506. mailProvider: prevState.mailProvider,
  5507. emailGenerator: prevState.emailGenerator,
  5508. emailPrefix: prevState.emailPrefix,
  5509. inbucketHost: prevState.inbucketHost,
  5510. inbucketMailbox: prevState.inbucketMailbox,
  5511. cloudflareDomain: prevState.cloudflareDomain,
  5512. cloudflareDomains: prevState.cloudflareDomains,
  5513. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  5514. tabRegistry: {},
  5515. sourceLastUrls: {},
  5516. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun }),
  5517. };
  5518. await resetState();
  5519. await setState(keepSettings);
  5520. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => { });
  5521. await sleepWithStop(500);
  5522. } else {
  5523. await setState({
  5524. autoRunSkipFailures,
  5525. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  5526. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun }),
  5527. });
  5528. }
  5529. if (forceFreshTabsNextRun) {
  5530. await addLog(`上一轮尝试已放弃,当前开始第 ${targetRun}/${totalRuns} 轮第 ${attemptRun} 次尝试。`, 'warn');
  5531. forceFreshTabsNextRun = false;
  5532. }
  5533. try {
  5534. throwIfStopped();
  5535. await broadcastAutoRunStatus('running', {
  5536. currentRun: targetRun,
  5537. totalRuns,
  5538. attemptRun,
  5539. });
  5540. await runAutoSequenceFromStep(startStep, {
  5541. targetRun,
  5542. totalRuns,
  5543. attemptRuns: attemptRun,
  5544. continued: useExistingProgress,
  5545. });
  5546. roundSummary.status = 'success';
  5547. roundSummary.finalFailureReason = '';
  5548. successfulRuns += 1;
  5549. await setState({
  5550. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  5551. });
  5552. await addLog(`=== 第 ${targetRun}/${totalRuns} 轮完成(第 ${attemptRun} 次尝试成功)===`, 'ok');
  5553. break;
  5554. } catch (err) {
  5555. if (isStopError(err)) {
  5556. stoppedEarly = true;
  5557. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  5558. await broadcastAutoRunStatus('stopped', {
  5559. currentRun: targetRun,
  5560. totalRuns,
  5561. attemptRun,
  5562. });
  5563. break;
  5564. }
  5565. const reason = getErrorMessage(err);
  5566. roundSummary.failureReasons.push(reason);
  5567. const canRetry = autoRunSkipFailures && attemptRun < maxAttemptsForRound;
  5568. await setState({
  5569. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  5570. });
  5571. if (canRetry) {
  5572. const retryIndex = attemptRun;
  5573. if (isRestartCurrentAttemptError(err)) {
  5574. await addLog(`第 ${targetRun}/${totalRuns} 轮第 ${attemptRun} 次尝试需要整轮重开:${reason}`, 'warn');
  5575. } else {
  5576. await addLog(`第 ${targetRun}/${totalRuns} 轮第 ${attemptRun} 次尝试失败:${reason}`, 'error');
  5577. }
  5578. cancelPendingCommands('当前尝试已放弃。');
  5579. await broadcastStopToContentScripts();
  5580. await broadcastAutoRunStatus('retrying', {
  5581. currentRun: targetRun,
  5582. totalRuns,
  5583. attemptRun,
  5584. });
  5585. forceFreshTabsNextRun = true;
  5586. await addLog(
  5587. `自动重试:${Math.round(AUTO_RUN_RETRY_DELAY_MS / 1000)} 秒后开始第 ${targetRun}/${totalRuns} 轮第 ${attemptRun + 1} 次尝试(第 ${retryIndex}/${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试)。`,
  5588. 'warn'
  5589. );
  5590. try {
  5591. await sleepWithStop(AUTO_RUN_RETRY_DELAY_MS);
  5592. } catch (sleepError) {
  5593. if (isStopError(sleepError)) {
  5594. stoppedEarly = true;
  5595. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  5596. await broadcastAutoRunStatus('stopped', {
  5597. currentRun: targetRun,
  5598. totalRuns,
  5599. attemptRun,
  5600. });
  5601. break;
  5602. }
  5603. throw sleepError;
  5604. }
  5605. try {
  5606. const parkedForRetry = await waitBeforeAutoRunRetry(targetRun, totalRuns, attemptRun + 1, {
  5607. autoRunSkipFailures,
  5608. roundSummaries,
  5609. });
  5610. if (parkedForRetry) {
  5611. parkedByTimer = true;
  5612. break;
  5613. }
  5614. } catch (sleepError) {
  5615. if (isStopError(sleepError)) {
  5616. stoppedEarly = true;
  5617. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  5618. await broadcastAutoRunStatus('stopped', {
  5619. currentRun: targetRun,
  5620. totalRuns,
  5621. attemptRun,
  5622. });
  5623. break;
  5624. }
  5625. throw sleepError;
  5626. }
  5627. attemptRun += 1;
  5628. reuseExistingProgress = false;
  5629. continue;
  5630. }
  5631. roundSummary.status = 'failed';
  5632. roundSummary.finalFailureReason = reason;
  5633. await setState({
  5634. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  5635. });
  5636. if (!autoRunSkipFailures) {
  5637. cancelPendingCommands('当前轮执行失败。');
  5638. await broadcastStopToContentScripts();
  5639. await addLog('自动重试未开启,自动运行将在当前失败后停止。', 'warn');
  5640. stoppedEarly = true;
  5641. await broadcastAutoRunStatus('stopped', {
  5642. currentRun: targetRun,
  5643. totalRuns,
  5644. attemptRun,
  5645. });
  5646. break;
  5647. }
  5648. await addLog(`第 ${targetRun}/${totalRuns} 轮最终失败:${reason}`, 'error');
  5649. await addLog(
  5650. targetRun < totalRuns
  5651. ? `第 ${targetRun}/${totalRuns} 轮已达到 ${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试上限,继续下一轮。`
  5652. : `第 ${targetRun}/${totalRuns} 轮已达到 ${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试上限,本次自动运行结束。`,
  5653. 'warn'
  5654. );
  5655. cancelPendingCommands('当前轮已达到重试上限。');
  5656. await broadcastStopToContentScripts();
  5657. forceFreshTabsNextRun = true;
  5658. break;
  5659. } finally {
  5660. reuseExistingProgress = false;
  5661. continueCurrentOnFirstAttempt = false;
  5662. }
  5663. }
  5664. if (stoppedEarly || parkedByTimer) {
  5665. break;
  5666. }
  5667. try {
  5668. const parkedForNextRound = await waitBetweenAutoRunRounds(targetRun, totalRuns, roundSummary, {
  5669. autoRunSkipFailures,
  5670. roundSummaries,
  5671. });
  5672. if (parkedForNextRound) {
  5673. parkedByTimer = true;
  5674. break;
  5675. }
  5676. } catch (sleepError) {
  5677. if (isStopError(sleepError)) {
  5678. stoppedEarly = true;
  5679. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  5680. await broadcastAutoRunStatus('stopped', {
  5681. currentRun: targetRun,
  5682. totalRuns,
  5683. attemptRun: autoRunAttemptRun,
  5684. });
  5685. break;
  5686. }
  5687. throw sleepError;
  5688. }
  5689. }
  5690. if (parkedByTimer) {
  5691. autoRunActive = false;
  5692. clearStopRequest();
  5693. return;
  5694. }
  5695. await setState({
  5696. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  5697. });
  5698. await logAutoRunFinalSummary(totalRuns, roundSummaries);
  5699. if (stopRequested || stoppedEarly) {
  5700. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮 ===`, 'warn');
  5701. await broadcastAutoRunStatus('stopped', {
  5702. currentRun: autoRunCurrentRun,
  5703. totalRuns: autoRunTotalRuns,
  5704. attemptRun: autoRunAttemptRun,
  5705. });
  5706. } else {
  5707. await addLog(`=== 全部 ${autoRunTotalRuns} 轮已执行完成,成功 ${successfulRuns} 轮 ===`, 'ok');
  5708. await broadcastAutoRunStatus('complete', {
  5709. currentRun: autoRunTotalRuns,
  5710. totalRuns: autoRunTotalRuns,
  5711. attemptRun: autoRunAttemptRun,
  5712. });
  5713. }
  5714. autoRunActive = false;
  5715. await setState({
  5716. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  5717. autoRunTimerPlan: null,
  5718. scheduledAutoRunPlan: null,
  5719. ...getAutoRunStatusPayload(stopRequested || stoppedEarly ? 'stopped' : 'complete', {
  5720. currentRun: stopRequested || stoppedEarly ? autoRunCurrentRun : autoRunTotalRuns,
  5721. totalRuns: autoRunTotalRuns,
  5722. attemptRun: autoRunAttemptRun,
  5723. }),
  5724. });
  5725. clearStopRequest();
  5726. }
  5727. async function resumeAutoRun() {
  5728. throwIfStopped();
  5729. const state = await getState();
  5730. if (!state.email) {
  5731. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  5732. return false;
  5733. }
  5734. const resumedInMemory = await resumeAutoRunIfWaitingForEmail({ silent: true });
  5735. if (resumedInMemory) {
  5736. return true;
  5737. }
  5738. if (!isAutoRunPausedState(state)) {
  5739. return false;
  5740. }
  5741. if (autoRunActive) {
  5742. return false;
  5743. }
  5744. const totalRuns = state.autoRunTotalRuns || 1;
  5745. const currentRun = state.autoRunCurrentRun || 1;
  5746. const attemptRun = state.autoRunAttemptRun || 1;
  5747. await addLog('检测到自动流程暂停上下文已丢失,正在从当前进度恢复自动运行...', 'warn');
  5748. startAutoRunLoop(totalRuns, {
  5749. autoRunSkipFailures: Boolean(state.autoRunSkipFailures),
  5750. mode: 'continue',
  5751. resumeCurrentRun: currentRun,
  5752. resumeAttemptRun: attemptRun,
  5753. resumeRoundSummaries: state.autoRunRoundSummaries,
  5754. });
  5755. return true;
  5756. }
  5757. // ============================================================
  5758. // Signup / OAuth Helpers
  5759. // ============================================================
  5760. const SIGNUP_ENTRY_URL = 'https://chatgpt.com/';
  5761. const SIGNUP_PAGE_INJECT_FILES = ['content/utils.js', 'content/signup-page.js'];
  5762. async function requestOAuthUrlFromPanel(state, options = {}) {
  5763. if (getPanelMode(state) === 'sub2api') {
  5764. return requestSub2ApiOAuthUrl(state, options);
  5765. }
  5766. return requestCpaOAuthUrl(state, options);
  5767. }
  5768. async function requestCpaOAuthUrl(state, options = {}) {
  5769. const { logLabel = 'OAuth 刷新' } = options;
  5770. if (!state.vpsUrl) {
  5771. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  5772. }
  5773. await addLog(`${logLabel}:正在打开 CPA 面板...`);
  5774. const injectFiles = ['content/activation-utils.js', 'content/utils.js', 'content/vps-panel.js'];
  5775. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  5776. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  5777. const tabId = tab.id;
  5778. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  5779. await addLog(`${logLabel}:CPA 面板已打开,正在等待页面进入目标地址...`);
  5780. const matchedTab = await waitForTabUrlFamily('vps-panel', tabId, state.vpsUrl, {
  5781. timeoutMs: 15000,
  5782. retryDelayMs: 400,
  5783. });
  5784. if (!matchedTab) {
  5785. await addLog(`${logLabel}:CPA 页面尚未完全进入目标地址,继续尝试连接内容脚本...`, 'warn');
  5786. }
  5787. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  5788. inject: injectFiles,
  5789. timeoutMs: 45000,
  5790. retryDelayMs: 900,
  5791. logMessage: `${logLabel}:CPA 面板仍在加载,正在重试连接内容脚本...`,
  5792. });
  5793. const result = await sendToContentScriptResilient('vps-panel', {
  5794. type: 'REQUEST_OAUTH_URL',
  5795. source: 'background',
  5796. payload: {
  5797. vpsPassword: state.vpsPassword,
  5798. logStep: 6,
  5799. },
  5800. }, {
  5801. timeoutMs: 30000,
  5802. retryDelayMs: 700,
  5803. logMessage: `${logLabel}:CPA 面板通信未就绪,正在等待页面恢复...`,
  5804. });
  5805. if (result?.error) {
  5806. throw new Error(result.error);
  5807. }
  5808. return result || {};
  5809. }
  5810. async function requestSub2ApiOAuthUrl(state, options = {}) {
  5811. const { logLabel = 'OAuth 刷新' } = options;
  5812. const sub2apiUrl = normalizeSub2ApiUrl(state.sub2apiUrl);
  5813. const groupName = (state.sub2apiGroupName || DEFAULT_SUB2API_GROUP_NAME).trim() || DEFAULT_SUB2API_GROUP_NAME;
  5814. if (!state.sub2apiEmail) {
  5815. throw new Error('尚未配置 SUB2API 登录邮箱,请先在侧边栏填写。');
  5816. }
  5817. if (!state.sub2apiPassword) {
  5818. throw new Error('尚未配置 SUB2API 登录密码,请先在侧边栏填写。');
  5819. }
  5820. await addLog(`${logLabel}:正在打开 SUB2API 后台...`);
  5821. const injectFiles = ['content/utils.js', 'content/sub2api-panel.js'];
  5822. await closeConflictingTabsForSource('sub2api-panel', sub2apiUrl);
  5823. const tab = await chrome.tabs.create({ url: sub2apiUrl, active: true });
  5824. const tabId = tab.id;
  5825. await rememberSourceLastUrl('sub2api-panel', sub2apiUrl);
  5826. await addLog(`${logLabel}:SUB2API 页面已打开,正在等待页面进入目标地址...`);
  5827. const matchedTab = await waitForTabUrlFamily('sub2api-panel', tabId, sub2apiUrl, {
  5828. timeoutMs: 15000,
  5829. retryDelayMs: 400,
  5830. });
  5831. if (!matchedTab) {
  5832. await addLog(`${logLabel}:SUB2API 页面尚未稳定,继续尝试连接内容脚本...`, 'warn');
  5833. }
  5834. await ensureContentScriptReadyOnTab('sub2api-panel', tabId, {
  5835. inject: injectFiles,
  5836. injectSource: 'sub2api-panel',
  5837. timeoutMs: 45000,
  5838. retryDelayMs: 900,
  5839. logMessage: `${logLabel}:SUB2API 页面仍在加载,正在重试连接内容脚本...`,
  5840. });
  5841. const result = await sendToContentScript('sub2api-panel', {
  5842. type: 'REQUEST_OAUTH_URL',
  5843. source: 'background',
  5844. payload: {
  5845. sub2apiUrl,
  5846. sub2apiEmail: state.sub2apiEmail,
  5847. sub2apiPassword: state.sub2apiPassword,
  5848. sub2apiGroupName: groupName,
  5849. logStep: 6,
  5850. },
  5851. }, {
  5852. responseTimeoutMs: SUB2API_STEP1_RESPONSE_TIMEOUT_MS,
  5853. });
  5854. if (result?.error) {
  5855. throw new Error(result.error);
  5856. }
  5857. return result || {};
  5858. }
  5859. async function openSignupEntryTab(step = 1) {
  5860. const tabId = await reuseOrCreateTab('signup-page', SIGNUP_ENTRY_URL, {
  5861. inject: SIGNUP_PAGE_INJECT_FILES,
  5862. injectSource: 'signup-page',
  5863. });
  5864. await ensureContentScriptReadyOnTab('signup-page', tabId, {
  5865. inject: SIGNUP_PAGE_INJECT_FILES,
  5866. injectSource: 'signup-page',
  5867. timeoutMs: 45000,
  5868. retryDelayMs: 900,
  5869. logMessage: `步骤 ${step}:ChatGPT 官网仍在加载,正在重试连接内容脚本...`,
  5870. });
  5871. return tabId;
  5872. }
  5873. async function ensureSignupEntryPageReady(step = 1) {
  5874. const tabId = await openSignupEntryTab(step);
  5875. const result = await sendToContentScriptResilient('signup-page', {
  5876. type: 'ENSURE_SIGNUP_ENTRY_READY',
  5877. step,
  5878. source: 'background',
  5879. payload: {},
  5880. }, {
  5881. timeoutMs: 20000,
  5882. retryDelayMs: 700,
  5883. logMessage: `步骤 ${step}:官网注册入口正在切换,等待页面恢复...`,
  5884. });
  5885. if (result?.error) {
  5886. throw new Error(result.error);
  5887. }
  5888. return { tabId, result: result || {} };
  5889. }
  5890. async function ensureSignupPasswordPageReadyInTab(tabId, step = 2, options = {}) {
  5891. const { skipUrlWait = false } = options;
  5892. if (!skipUrlWait) {
  5893. const matchedTab = await waitForTabUrlMatch(tabId, (url) => isSignupPasswordPageUrl(url), {
  5894. timeoutMs: 45000,
  5895. retryDelayMs: 300,
  5896. });
  5897. if (!matchedTab) {
  5898. throw new Error('等待进入密码页超时,请检查邮箱提交后页面是否仍停留在官网或邮箱页。');
  5899. }
  5900. }
  5901. await ensureContentScriptReadyOnTab('signup-page', tabId, {
  5902. inject: SIGNUP_PAGE_INJECT_FILES,
  5903. injectSource: 'signup-page',
  5904. timeoutMs: 45000,
  5905. retryDelayMs: 900,
  5906. logMessage: `步骤 ${step}:密码页仍在加载,正在重试连接内容脚本...`,
  5907. });
  5908. const result = await sendToContentScriptResilient('signup-page', {
  5909. type: 'ENSURE_SIGNUP_PASSWORD_PAGE_READY',
  5910. step,
  5911. source: 'background',
  5912. payload: {},
  5913. }, {
  5914. timeoutMs: 20000,
  5915. retryDelayMs: 700,
  5916. logMessage: `步骤 ${step}:认证页正在切换,等待密码页重新就绪...`,
  5917. });
  5918. if (result?.error) {
  5919. throw new Error(result.error);
  5920. }
  5921. return result || {};
  5922. }
  5923. async function resolveSignupEmailForFlow(state) {
  5924. let resolvedEmail = state.email;
  5925. if (isHotmailProvider(state)) {
  5926. const account = await ensureHotmailAccountForFlow({
  5927. allowAllocate: true,
  5928. markUsed: true,
  5929. preferredAccountId: state.currentHotmailAccountId || null,
  5930. });
  5931. resolvedEmail = account.email;
  5932. } else if (isLuckmailProvider(state)) {
  5933. const purchase = await ensureLuckmailPurchaseForFlow({ allowReuse: true });
  5934. resolvedEmail = purchase.email_address;
  5935. } else if (isGeneratedAliasProvider(state)) {
  5936. resolvedEmail = buildGeneratedAliasEmail(state);
  5937. }
  5938. if (!resolvedEmail) {
  5939. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  5940. }
  5941. return resolvedEmail;
  5942. }
  5943. // ============================================================
  5944. // Step 1: Open ChatGPT homepage
  5945. // ============================================================
  5946. async function executeStep1() {
  5947. await addLog('步骤 1:正在打开 ChatGPT 官网...');
  5948. await ensureSignupEntryPageReady(1);
  5949. await completeStepFromBackground(1, {});
  5950. }
  5951. // ============================================================
  5952. // Step 2: Click signup, fill email, continue to password page
  5953. // ============================================================
  5954. async function executeStep2(state) {
  5955. const resolvedEmail = await resolveSignupEmailForFlow(state);
  5956. if (resolvedEmail !== state.email) {
  5957. await setEmailState(resolvedEmail);
  5958. }
  5959. let signupTabId = await getTabId('signup-page');
  5960. if (!signupTabId || !(await isTabAlive('signup-page'))) {
  5961. await addLog('步骤 2:未发现可用的注册页标签,正在重新打开 ChatGPT 官网...', 'warn');
  5962. signupTabId = (await ensureSignupEntryPageReady(2)).tabId;
  5963. } else {
  5964. await chrome.tabs.update(signupTabId, { active: true });
  5965. await ensureContentScriptReadyOnTab('signup-page', signupTabId, {
  5966. inject: SIGNUP_PAGE_INJECT_FILES,
  5967. injectSource: 'signup-page',
  5968. timeoutMs: 45000,
  5969. retryDelayMs: 900,
  5970. logMessage: '步骤 2:注册入口页内容脚本未就绪,正在等待页面恢复...',
  5971. });
  5972. }
  5973. const step2Result = await sendToContentScriptResilient('signup-page', {
  5974. type: 'EXECUTE_STEP',
  5975. step: 2,
  5976. source: 'background',
  5977. payload: { email: resolvedEmail },
  5978. }, {
  5979. timeoutMs: 20000,
  5980. retryDelayMs: 700,
  5981. logMessage: '步骤 2:官网注册入口正在切换,等待页面恢复后继续输入邮箱...',
  5982. });
  5983. if (step2Result?.error) {
  5984. throw new Error(step2Result.error);
  5985. }
  5986. if (!step2Result?.alreadyOnPasswordPage) {
  5987. await addLog(`步骤 2:邮箱 ${resolvedEmail} 已提交,正在等待进入密码页...`);
  5988. }
  5989. await ensureSignupPasswordPageReadyInTab(signupTabId, 2, {
  5990. skipUrlWait: Boolean(step2Result?.alreadyOnPasswordPage),
  5991. });
  5992. await completeStepFromBackground(2, {});
  5993. }
  5994. // ============================================================
  5995. // Step 3: Fill Password (via signup-page.js)
  5996. // ============================================================
  5997. async function executeStep3(state) {
  5998. const resolvedEmail = state.email;
  5999. if (!resolvedEmail) {
  6000. throw new Error('缺少邮箱地址,请先完成步骤 2。');
  6001. }
  6002. const signupTabId = await getTabId('signup-page');
  6003. if (!signupTabId || !(await isTabAlive('signup-page'))) {
  6004. throw new Error('认证页面标签页已关闭,请先重新完成步骤 2。');
  6005. }
  6006. const password = state.customPassword || generatePassword();
  6007. await setPasswordState(password);
  6008. const accounts = state.accounts || [];
  6009. accounts.push({ email: resolvedEmail, password, createdAt: new Date().toISOString() });
  6010. await setState({ accounts });
  6011. await chrome.tabs.update(signupTabId, { active: true });
  6012. await ensureContentScriptReadyOnTab('signup-page', signupTabId, {
  6013. inject: SIGNUP_PAGE_INJECT_FILES,
  6014. injectSource: 'signup-page',
  6015. timeoutMs: 45000,
  6016. retryDelayMs: 900,
  6017. logMessage: '步骤 3:密码页内容脚本未就绪,正在等待页面恢复...',
  6018. });
  6019. await addLog(
  6020. `步骤 3:正在填写密码,邮箱为 ${resolvedEmail},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  6021. );
  6022. await sendToContentScript('signup-page', {
  6023. type: 'EXECUTE_STEP',
  6024. step: 3,
  6025. source: 'background',
  6026. payload: { email: resolvedEmail, password },
  6027. });
  6028. }
  6029. // ============================================================
  6030. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  6031. // ============================================================
  6032. function getMailConfig(state) {
  6033. const provider = state.mailProvider || 'qq';
  6034. if (provider === 'custom') {
  6035. return { provider: 'custom', label: '自定义邮箱' };
  6036. }
  6037. if (provider === HOTMAIL_PROVIDER) {
  6038. return { provider: HOTMAIL_PROVIDER, label: 'Hotmail(API对接/本地助手)' };
  6039. }
  6040. if (provider === ICLOUD_PROVIDER) {
  6041. const configuredHost = getConfiguredIcloudHostPreference(state)
  6042. || normalizeIcloudHost(state?.preferredIcloudHost)
  6043. || 'icloud.com';
  6044. const loginUrl = getIcloudLoginUrlForHost(configuredHost) || 'https://www.icloud.com/';
  6045. const mailUrl = getIcloudMailUrlForHost(configuredHost) || loginUrl;
  6046. return {
  6047. source: 'icloud-mail',
  6048. url: mailUrl,
  6049. label: 'iCloud 邮箱',
  6050. navigateOnReuse: true,
  6051. };
  6052. }
  6053. if (provider === GMAIL_PROVIDER) {
  6054. return {
  6055. source: 'gmail-mail',
  6056. url: 'https://mail.google.com/mail/u/0/#inbox',
  6057. label: 'Gmail 邮箱',
  6058. inject: ['content/activation-utils.js', 'content/utils.js', 'content/gmail-mail.js'],
  6059. injectSource: 'gmail-mail',
  6060. };
  6061. }
  6062. if (provider === LUCKMAIL_PROVIDER) {
  6063. return { provider: LUCKMAIL_PROVIDER, label: 'LuckMail(API 购邮)' };
  6064. }
  6065. if (provider === CLOUDFLARE_TEMP_EMAIL_PROVIDER) {
  6066. return { provider: CLOUDFLARE_TEMP_EMAIL_PROVIDER, label: 'Cloudflare Temp Email' };
  6067. }
  6068. if (provider === '163') {
  6069. 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 邮箱' };
  6070. }
  6071. if (provider === '163-vip') {
  6072. 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 邮箱' };
  6073. }
  6074. if (provider === 'inbucket') {
  6075. const host = normalizeInbucketOrigin(state.inbucketHost);
  6076. const mailbox = (state.inbucketMailbox || '').trim();
  6077. if (!host) {
  6078. return { error: 'Inbucket 主机地址为空或无效。' };
  6079. }
  6080. if (!mailbox) {
  6081. return { error: 'Inbucket 邮箱名称为空。' };
  6082. }
  6083. return {
  6084. source: 'inbucket-mail',
  6085. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  6086. label: `Inbucket 邮箱(${mailbox})`,
  6087. navigateOnReuse: true,
  6088. inject: ['content/activation-utils.js', 'content/utils.js', 'content/inbucket-mail.js'],
  6089. injectSource: 'inbucket-mail',
  6090. };
  6091. }
  6092. if (provider === '2925') {
  6093. return {
  6094. source: 'mail-2925',
  6095. url: 'https://2925.com/#/mailList',
  6096. label: '2925 邮箱',
  6097. inject: ['content/utils.js', 'content/mail-2925.js'],
  6098. injectSource: 'mail-2925',
  6099. };
  6100. }
  6101. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  6102. }
  6103. function normalizeInbucketOrigin(rawValue) {
  6104. const value = (rawValue || '').trim();
  6105. if (!value) return '';
  6106. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  6107. try {
  6108. const parsed = new URL(candidate);
  6109. return parsed.origin;
  6110. } catch {
  6111. return '';
  6112. }
  6113. }
  6114. function getVerificationCodeStateKey(step) {
  6115. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  6116. }
  6117. function getVerificationCodeLabel(step) {
  6118. return step === 4 ? '注册' : '登录';
  6119. }
  6120. async function confirmCustomVerificationStepBypass(step) {
  6121. const verificationLabel = getVerificationCodeLabel(step);
  6122. await addLog(`步骤 ${step}:当前为自定义邮箱模式,请手动在页面中输入${verificationLabel}验证码并进入下一页面。`, 'warn');
  6123. let response = null;
  6124. try {
  6125. response = await chrome.runtime.sendMessage({
  6126. type: 'REQUEST_CUSTOM_VERIFICATION_BYPASS_CONFIRMATION',
  6127. payload: { step },
  6128. });
  6129. } catch {
  6130. throw new Error(`步骤 ${step}:无法打开确认弹窗,请先保持侧边栏打开后重试。`);
  6131. }
  6132. if (response?.error) {
  6133. throw new Error(response.error);
  6134. }
  6135. if (!response?.confirmed) {
  6136. throw new Error(`步骤 ${step}:已取消手动${verificationLabel}验证码确认。`);
  6137. }
  6138. await setState({
  6139. lastEmailTimestamp: null,
  6140. signupVerificationRequestedAt: null,
  6141. loginVerificationRequestedAt: null,
  6142. });
  6143. await setStepStatus(step, 'skipped');
  6144. await addLog(`步骤 ${step}:已确认手动完成${verificationLabel}验证码输入,当前步骤已跳过。`, 'warn');
  6145. }
  6146. function getVerificationPollPayload(step, state, overrides = {}) {
  6147. if (step === 4) {
  6148. return {
  6149. filterAfterTimestamp: getHotmailVerificationRequestTimestamp(4, state),
  6150. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  6151. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  6152. targetEmail: state.email,
  6153. maxAttempts: 5,
  6154. intervalMs: 3000,
  6155. ...overrides,
  6156. };
  6157. }
  6158. return {
  6159. filterAfterTimestamp: getHotmailVerificationRequestTimestamp(7, state),
  6160. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  6161. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  6162. targetEmail: state.email,
  6163. maxAttempts: 5,
  6164. intervalMs: 3000,
  6165. ...overrides,
  6166. };
  6167. }
  6168. async function requestVerificationCodeResend(step) {
  6169. throwIfStopped();
  6170. const signupTabId = await getTabId('signup-page');
  6171. if (!signupTabId) {
  6172. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  6173. }
  6174. throwIfStopped();
  6175. await chrome.tabs.update(signupTabId, { active: true });
  6176. throwIfStopped();
  6177. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  6178. throwIfStopped();
  6179. const result = await sendToContentScript('signup-page', {
  6180. type: 'RESEND_VERIFICATION_CODE',
  6181. step,
  6182. source: 'background',
  6183. payload: {},
  6184. });
  6185. if (result && result.error) {
  6186. throw new Error(result.error);
  6187. }
  6188. const requestedAt = Date.now();
  6189. if (step === 7) {
  6190. await setState({ loginVerificationRequestedAt: requestedAt });
  6191. }
  6192. const currentState = await getState();
  6193. if (currentState.mailProvider === '2925') {
  6194. const mailTabId = await getTabId('mail-2925');
  6195. if (mailTabId) {
  6196. await chrome.tabs.update(mailTabId, { active: true });
  6197. await addLog(`步骤 ${step}:已切换到 2925 邮箱标签页等待新邮件。`, 'info');
  6198. }
  6199. }
  6200. return requestedAt;
  6201. }
  6202. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  6203. const { onResendRequestedAt, ...cleanPollOverrides } = pollOverrides;
  6204. if (mail.provider === HOTMAIL_PROVIDER) {
  6205. const hotmailPollConfig = getHotmailVerificationPollConfig(step);
  6206. return pollHotmailVerificationCode(step, state, {
  6207. ...getVerificationPollPayload(step, state),
  6208. ...hotmailPollConfig,
  6209. ...cleanPollOverrides,
  6210. });
  6211. }
  6212. if (mail.provider === LUCKMAIL_PROVIDER) {
  6213. return pollLuckmailVerificationCode(step, state, {
  6214. ...getVerificationPollPayload(step, state),
  6215. ...pollOverrides,
  6216. });
  6217. }
  6218. if (mail.provider === CLOUDFLARE_TEMP_EMAIL_PROVIDER) {
  6219. return pollCloudflareTempEmailVerificationCode(step, state, {
  6220. ...getVerificationPollPayload(step, state),
  6221. ...pollOverrides,
  6222. });
  6223. }
  6224. if (Number(pollOverrides.resendIntervalMs) > 0) {
  6225. return pollFreshVerificationCodeWithResendInterval(step, state, mail, pollOverrides);
  6226. }
  6227. const stateKey = getVerificationCodeStateKey(step);
  6228. const rejectedCodes = new Set();
  6229. if (state[stateKey]) {
  6230. rejectedCodes.add(state[stateKey]);
  6231. }
  6232. for (const code of (pollOverrides.excludeCodes || [])) {
  6233. if (code) rejectedCodes.add(code);
  6234. }
  6235. let lastError = null;
  6236. let filterAfterTimestamp = cleanPollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  6237. const maxRounds = pollOverrides.maxRounds || VERIFICATION_POLL_MAX_ROUNDS;
  6238. for (let round = 1; round <= maxRounds; round++) {
  6239. throwIfStopped();
  6240. if (round > 1) {
  6241. const requestedAt = await requestVerificationCodeResend(step);
  6242. if (typeof onResendRequestedAt === 'function') {
  6243. const nextFilterAfterTimestamp = await onResendRequestedAt(requestedAt);
  6244. if (nextFilterAfterTimestamp !== undefined) {
  6245. filterAfterTimestamp = nextFilterAfterTimestamp;
  6246. }
  6247. }
  6248. }
  6249. const payload = getVerificationPollPayload(step, state, {
  6250. ...cleanPollOverrides,
  6251. filterAfterTimestamp,
  6252. excludeCodes: [...rejectedCodes],
  6253. });
  6254. try {
  6255. const result = await sendToMailContentScriptResilient(
  6256. mail,
  6257. {
  6258. type: 'POLL_EMAIL',
  6259. step,
  6260. source: 'background',
  6261. payload,
  6262. },
  6263. {
  6264. timeoutMs: 45000,
  6265. maxRecoveryAttempts: 2,
  6266. }
  6267. );
  6268. if (result && result.error) {
  6269. throw new Error(result.error);
  6270. }
  6271. if (!result || !result.code) {
  6272. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  6273. }
  6274. if (rejectedCodes.has(result.code)) {
  6275. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  6276. }
  6277. return result;
  6278. } catch (err) {
  6279. if (isStopError(err)) {
  6280. throw err;
  6281. }
  6282. lastError = err;
  6283. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  6284. if (round < maxRounds) {
  6285. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  6286. }
  6287. }
  6288. }
  6289. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  6290. }
  6291. async function pollFreshVerificationCodeWithResendInterval(step, state, mail, pollOverrides = {}) {
  6292. const stateKey = getVerificationCodeStateKey(step);
  6293. const rejectedCodes = new Set();
  6294. if (state[stateKey]) {
  6295. rejectedCodes.add(state[stateKey]);
  6296. }
  6297. for (const code of (pollOverrides.excludeCodes || [])) {
  6298. if (code) rejectedCodes.add(code);
  6299. }
  6300. const {
  6301. maxRounds: _ignoredMaxRounds,
  6302. resendIntervalMs: _ignoredResendIntervalMs,
  6303. lastResendAt: _ignoredLastResendAt,
  6304. onResendRequestedAt: _ignoredOnResendRequestedAt,
  6305. ...payloadOverrides
  6306. } = pollOverrides;
  6307. const onResendRequestedAt = typeof pollOverrides.onResendRequestedAt === 'function'
  6308. ? pollOverrides.onResendRequestedAt
  6309. : null;
  6310. let lastError = null;
  6311. let filterAfterTimestamp = payloadOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  6312. const maxRounds = pollOverrides.maxRounds || VERIFICATION_POLL_MAX_ROUNDS;
  6313. const resendIntervalMs = Math.max(0, Number(pollOverrides.resendIntervalMs) || 0);
  6314. let lastResendAt = Number(pollOverrides.lastResendAt) || 0;
  6315. for (let round = 1; round <= maxRounds; round++) {
  6316. throwIfStopped();
  6317. if (round > 1) {
  6318. lastResendAt = await requestVerificationCodeResend(step);
  6319. if (onResendRequestedAt) {
  6320. const nextFilterAfterTimestamp = await onResendRequestedAt(lastResendAt);
  6321. if (nextFilterAfterTimestamp !== undefined) {
  6322. filterAfterTimestamp = nextFilterAfterTimestamp;
  6323. }
  6324. }
  6325. }
  6326. while (true) {
  6327. throwIfStopped();
  6328. const payload = getVerificationPollPayload(step, state, {
  6329. ...payloadOverrides,
  6330. filterAfterTimestamp,
  6331. excludeCodes: [...rejectedCodes],
  6332. });
  6333. if (lastResendAt > 0) {
  6334. const remainingBeforeResendMs = Math.max(0, resendIntervalMs - (Date.now() - lastResendAt));
  6335. const baseMaxAttempts = Math.max(1, Number(payload.maxAttempts) || 5);
  6336. const intervalMs = Math.max(1, Number(payload.intervalMs) || 3000);
  6337. payload.maxAttempts = Math.max(1, Math.min(baseMaxAttempts, Math.floor(remainingBeforeResendMs / intervalMs) + 1));
  6338. }
  6339. try {
  6340. const result = await sendToMailContentScriptResilient(
  6341. mail,
  6342. {
  6343. type: 'POLL_EMAIL',
  6344. step,
  6345. source: 'background',
  6346. payload,
  6347. },
  6348. {
  6349. timeoutMs: 45000,
  6350. maxRecoveryAttempts: 2,
  6351. }
  6352. );
  6353. if (result && result.error) {
  6354. throw new Error(result.error);
  6355. }
  6356. if (!result || !result.code) {
  6357. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  6358. }
  6359. if (rejectedCodes.has(result.code)) {
  6360. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  6361. }
  6362. return {
  6363. ...result,
  6364. lastResendAt,
  6365. };
  6366. } catch (err) {
  6367. if (isStopError(err)) {
  6368. throw err;
  6369. }
  6370. lastError = err;
  6371. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  6372. }
  6373. const remainingBeforeResendMs = lastResendAt > 0
  6374. ? Math.max(0, resendIntervalMs - (Date.now() - lastResendAt))
  6375. : 0;
  6376. if (remainingBeforeResendMs > 0) {
  6377. await addLog(
  6378. `步骤 ${step}:距离下次重新发送验证码还差 ${Math.ceil(remainingBeforeResendMs / 1000)} 秒,继续刷新邮箱(第 ${round}/${maxRounds} 轮)...`,
  6379. 'info'
  6380. );
  6381. continue;
  6382. }
  6383. if (round < maxRounds) {
  6384. await addLog(`步骤 ${step}:已到 25 秒重发间隔,准备重新发送验证码(第 ${round + 1}/${maxRounds} 轮)...`, 'warn');
  6385. }
  6386. break;
  6387. }
  6388. }
  6389. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  6390. }
  6391. async function submitVerificationCode(step, code) {
  6392. const signupTabId = await getTabId('signup-page');
  6393. if (!signupTabId) {
  6394. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  6395. }
  6396. await chrome.tabs.update(signupTabId, { active: true });
  6397. const result = await sendToContentScript('signup-page', {
  6398. type: 'FILL_CODE',
  6399. step,
  6400. source: 'background',
  6401. payload: { code },
  6402. });
  6403. if (result && result.error) {
  6404. throw new Error(result.error);
  6405. }
  6406. return result || {};
  6407. }
  6408. async function resolveVerificationStep(step, state, mail, options = {}) {
  6409. const stateKey = getVerificationCodeStateKey(step);
  6410. const rejectedCodes = new Set();
  6411. const hotmailPollConfig = mail.provider === HOTMAIL_PROVIDER
  6412. ? getHotmailVerificationPollConfig(step)
  6413. : null;
  6414. const ignorePersistedLastCode = Boolean(hotmailPollConfig?.ignorePersistedLastCode);
  6415. if (state[stateKey] && !ignorePersistedLastCode) {
  6416. rejectedCodes.add(state[stateKey]);
  6417. }
  6418. let nextFilterAfterTimestamp = options.filterAfterTimestamp ?? null;
  6419. const requestFreshCodeFirst = options.requestFreshCodeFirst !== undefined
  6420. ? Boolean(options.requestFreshCodeFirst)
  6421. : (hotmailPollConfig?.requestFreshCodeFirst ?? false);
  6422. const maxSubmitAttempts = 3;
  6423. const resendIntervalMs = Math.max(0, Number(options.resendIntervalMs) || 0);
  6424. let lastResendAt = Number(options.lastResendAt) || 0;
  6425. const updateFilterAfterTimestampForStep7 = async (requestedAt) => {
  6426. if (step !== 7 || !requestedAt) {
  6427. return nextFilterAfterTimestamp;
  6428. }
  6429. if (mail.provider === HOTMAIL_PROVIDER) {
  6430. nextFilterAfterTimestamp = getHotmailVerificationRequestTimestamp(7, {
  6431. ...state,
  6432. loginVerificationRequestedAt: requestedAt,
  6433. });
  6434. } else {
  6435. nextFilterAfterTimestamp = Math.max(0, Number(requestedAt) - 60000);
  6436. }
  6437. return nextFilterAfterTimestamp;
  6438. };
  6439. if (requestFreshCodeFirst) {
  6440. try {
  6441. lastResendAt = await requestVerificationCodeResend(step);
  6442. await updateFilterAfterTimestampForStep7(lastResendAt);
  6443. await addLog(`步骤 ${step}:已先请求一封新的${getVerificationCodeLabel(step)}验证码,再开始轮询邮箱。`, 'warn');
  6444. } catch (err) {
  6445. if (isStopError(err)) {
  6446. throw err;
  6447. }
  6448. await addLog(`步骤 ${step}:首次重新获取验证码失败:${err.message},将继续使用当前时间窗口轮询。`, 'warn');
  6449. }
  6450. }
  6451. if (mail.provider === HOTMAIL_PROVIDER) {
  6452. const initialDelayMs = Number(options.initialDelayMs ?? hotmailPollConfig.initialDelayMs) || 0;
  6453. if (initialDelayMs > 0) {
  6454. await addLog(`步骤 ${step}:等待 ${Math.round(initialDelayMs / 1000)} 秒,让 Hotmail 验证码邮件先到达...`, 'info');
  6455. await sleepWithStop(initialDelayMs);
  6456. }
  6457. }
  6458. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  6459. const result = await pollFreshVerificationCode(step, state, mail, {
  6460. excludeCodes: [...rejectedCodes],
  6461. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  6462. resendIntervalMs,
  6463. lastResendAt,
  6464. onResendRequestedAt: updateFilterAfterTimestampForStep7,
  6465. });
  6466. lastResendAt = Number(result?.lastResendAt) || lastResendAt;
  6467. throwIfStopped();
  6468. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  6469. throwIfStopped();
  6470. const submitResult = await submitVerificationCode(step, result.code);
  6471. if (submitResult.invalidCode) {
  6472. rejectedCodes.add(result.code);
  6473. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  6474. if (attempt >= maxSubmitAttempts) {
  6475. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  6476. }
  6477. const remainingBeforeResendMs = resendIntervalMs > 0 && lastResendAt > 0
  6478. ? Math.max(0, resendIntervalMs - (Date.now() - lastResendAt))
  6479. : 0;
  6480. if (remainingBeforeResendMs > 0) {
  6481. await addLog(
  6482. `步骤 ${step}:提交失败后距离下次重新发送验证码还差 ${Math.ceil(remainingBeforeResendMs / 1000)} 秒,先继续刷新邮箱(${attempt + 1}/${maxSubmitAttempts})...`,
  6483. 'warn'
  6484. );
  6485. continue;
  6486. }
  6487. lastResendAt = await requestVerificationCodeResend(step);
  6488. await updateFilterAfterTimestampForStep7(lastResendAt);
  6489. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  6490. continue;
  6491. }
  6492. await setState({
  6493. lastEmailTimestamp: result.emailTimestamp,
  6494. [stateKey]: result.code,
  6495. });
  6496. await completeStepFromBackground(step, {
  6497. emailTimestamp: result.emailTimestamp,
  6498. code: result.code,
  6499. });
  6500. return;
  6501. }
  6502. }
  6503. async function executeStep4(state) {
  6504. const mail = getMailConfig(state);
  6505. if (mail.error) throw new Error(mail.error);
  6506. const stepStartedAt = Date.now();
  6507. const signupTabId = await getTabId('signup-page');
  6508. if (!signupTabId) {
  6509. throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
  6510. }
  6511. await chrome.tabs.update(signupTabId, { active: true });
  6512. throwIfStopped();
  6513. await addLog('步骤 4:正在确认注册验证码页面是否就绪,必要时自动恢复密码页超时报错...');
  6514. const prepareResult = await sendToContentScriptResilient(
  6515. 'signup-page',
  6516. {
  6517. type: 'PREPARE_SIGNUP_VERIFICATION',
  6518. step: 4,
  6519. source: 'background',
  6520. payload: { password: state.password || state.customPassword || '' },
  6521. },
  6522. {
  6523. timeoutMs: 30000,
  6524. retryDelayMs: 700,
  6525. logMessage: '步骤 4:认证页正在切换,等待页面重新就绪后继续检测...',
  6526. }
  6527. );
  6528. if (prepareResult && prepareResult.error) {
  6529. throw new Error(prepareResult.error);
  6530. }
  6531. if (prepareResult?.alreadyVerified) {
  6532. await completeStepFromBackground(4, {});
  6533. return;
  6534. }
  6535. if (shouldUseCustomRegistrationEmail(state)) {
  6536. await confirmCustomVerificationStepBypass(4);
  6537. return;
  6538. }
  6539. throwIfStopped();
  6540. if (mail.provider === HOTMAIL_PROVIDER || mail.provider === LUCKMAIL_PROVIDER || mail.provider === CLOUDFLARE_TEMP_EMAIL_PROVIDER) {
  6541. await addLog(`步骤 4:正在通过 ${mail.label} 轮询验证码...`);
  6542. } else {
  6543. await addLog(`步骤 4:正在打开${mail.label}...`);
  6544. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  6545. const alive = await isTabAlive(mail.source);
  6546. if (alive) {
  6547. if (mail.navigateOnReuse) {
  6548. await reuseOrCreateTab(mail.source, mail.url, {
  6549. inject: mail.inject,
  6550. injectSource: mail.injectSource,
  6551. });
  6552. } else {
  6553. const tabId = await getTabId(mail.source);
  6554. await chrome.tabs.update(tabId, { active: true });
  6555. }
  6556. } else {
  6557. await reuseOrCreateTab(mail.source, mail.url, {
  6558. inject: mail.inject,
  6559. injectSource: mail.injectSource,
  6560. });
  6561. }
  6562. }
  6563. await resolveVerificationStep(4, state, mail, {
  6564. filterAfterTimestamp: mail.provider === HOTMAIL_PROVIDER ? undefined : stepStartedAt,
  6565. requestFreshCodeFirst: mail.provider === HOTMAIL_PROVIDER ? false : true,
  6566. resendIntervalMs: mail.provider === HOTMAIL_PROVIDER ? 0 : STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS,
  6567. });
  6568. return;
  6569. }
  6570. // ============================================================
  6571. // Step 5: Fill Name & Birthday (via signup-page.js)
  6572. // ============================================================
  6573. async function waitForStep5ChatgptRedirect(tabId, timeoutMs = 15000) {
  6574. if (!Number.isInteger(tabId)) {
  6575. return null;
  6576. }
  6577. const matchedTab = await waitForTabUrlMatch(tabId, (url) => /chatgpt\.com/i.test(url || ''), {
  6578. timeoutMs,
  6579. retryDelayMs: 300,
  6580. });
  6581. if (matchedTab) {
  6582. return matchedTab;
  6583. }
  6584. const currentTab = await chrome.tabs.get(tabId).catch(() => null);
  6585. if (currentTab && /chatgpt\.com/i.test(currentTab.url || '')) {
  6586. return currentTab;
  6587. }
  6588. return null;
  6589. }
  6590. async function executeStep5(state) {
  6591. const { firstName, lastName } = generateRandomName();
  6592. const { year, month, day } = generateRandomBirthday();
  6593. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  6594. let step5Result = null;
  6595. let step5TransportError = null;
  6596. try {
  6597. step5Result = await sendToContentScript('signup-page', {
  6598. type: 'EXECUTE_STEP',
  6599. step: 5,
  6600. source: 'background',
  6601. payload: { firstName, lastName, year, month, day },
  6602. });
  6603. } catch (err) {
  6604. // Cross-origin navigation (auth page → chatgpt.com) destroys the content
  6605. // script, causing a transport error. Capture it so we can check if the tab
  6606. // ended up on chatgpt.com onboarding.
  6607. if (isRetryableContentScriptTransportError(err)) {
  6608. step5TransportError = err;
  6609. console.log(LOG_PREFIX, '步骤 5:内容脚本通信中断,正在检查是否跳转到 ChatGPT 引导页...', err?.message);
  6610. } else {
  6611. throw err;
  6612. }
  6613. }
  6614. // Case 1: content script successfully detected chatgpt redirect before dying
  6615. if (step5Result?.chatgptOnboarding) {
  6616. await addLog('步骤 5:检测到 ChatGPT 引导页跳转,正在处理引导页跳过...');
  6617. await handleChatgptOnboardingSkip();
  6618. return;
  6619. }
  6620. if (step5Result?.chatgptHome) {
  6621. await addLog('步骤 5:检测到已进入 ChatGPT 页面,注册成功。', 'ok');
  6622. return;
  6623. }
  6624. // Case 2: content script died due to cross-origin navigation — check tab URL
  6625. if (step5TransportError) {
  6626. const signupTabId = await getTabId('signup-page');
  6627. const redirectedTab = await waitForStep5ChatgptRedirect(signupTabId);
  6628. if (redirectedTab) {
  6629. await addLog('步骤 5:内容脚本因页面跳转到 ChatGPT 而断开,正在处理引导页跳过...');
  6630. await handleChatgptOnboardingSkip(redirectedTab.id);
  6631. return;
  6632. }
  6633. // Not on chatgpt.com — re-throw the original error
  6634. throw step5TransportError;
  6635. }
  6636. }
  6637. async function handleChatgptOnboardingSkip(knownTabId) {
  6638. const signupTabId = knownTabId || await getTabId('signup-page');
  6639. if (!signupTabId) {
  6640. throw new Error('步骤 5:无法找到注册页标签页,无法处理 ChatGPT 引导页。');
  6641. }
  6642. // Wait for the tab to navigate to chatgpt.com (may already be there)
  6643. const start = Date.now();
  6644. const timeout = 15000;
  6645. let tabUrl = '';
  6646. while (Date.now() - start < timeout) {
  6647. throwIfStopped();
  6648. const tab = await chrome.tabs.get(signupTabId).catch(() => null);
  6649. if (tab && /chatgpt\.com/i.test(tab.url || '')) {
  6650. tabUrl = tab.url;
  6651. break;
  6652. }
  6653. await sleepWithStop(500);
  6654. }
  6655. if (!tabUrl) {
  6656. throw new Error('步骤 5:等待页面跳转到 ChatGPT 引导页超时。');
  6657. }
  6658. // Wait for page to finish loading
  6659. await sleepWithStop(2000);
  6660. // Inject content script on chatgpt.com
  6661. await ensureContentScriptReadyOnTab('signup-page', signupTabId, {
  6662. inject: SIGNUP_PAGE_INJECT_FILES,
  6663. injectSource: 'signup-page',
  6664. timeoutMs: 15000,
  6665. logMessage: '步骤 5:正在等待 ChatGPT 引导页内容脚本就绪...',
  6666. });
  6667. // Send CHATGPT_SKIP_ONBOARDING message
  6668. const result = await sendToContentScriptResilient('signup-page', {
  6669. type: 'CHATGPT_SKIP_ONBOARDING',
  6670. source: 'background',
  6671. payload: {},
  6672. }, {
  6673. timeoutMs: 60000,
  6674. retryDelayMs: 1000,
  6675. logMessage: '步骤 5:ChatGPT 引导页正在处理,等待跳过完成...',
  6676. });
  6677. if (result?.error) {
  6678. throw new Error(result.error);
  6679. }
  6680. if (result?.alreadyCompleted) {
  6681. await addLog('步骤 5:已进入 ChatGPT 页面,无需继续跳过引导,注册成功。', 'ok');
  6682. await completeStepFromBackground(5, { chatgptHome: true });
  6683. return;
  6684. }
  6685. await addLog('步骤 5:ChatGPT 引导页跳过完成,注册成功。', 'ok');
  6686. await completeStepFromBackground(5, { chatgptOnboarding: true });
  6687. }
  6688. // ============================================================
  6689. // Step 6 Cookie Cleanup
  6690. // ============================================================
  6691. function normalizeCookieDomainForMatch(domain) {
  6692. return String(domain || '').trim().replace(/^\.+/, '').toLowerCase();
  6693. }
  6694. function shouldClearPreLoginCookie(cookie) {
  6695. const domain = normalizeCookieDomainForMatch(cookie?.domain);
  6696. if (!domain) return false;
  6697. return PRE_LOGIN_COOKIE_CLEAR_DOMAINS.some((target) => (
  6698. domain === target || domain.endsWith(`.${target}`)
  6699. ));
  6700. }
  6701. function buildCookieRemovalUrl(cookie) {
  6702. const host = normalizeCookieDomainForMatch(cookie?.domain);
  6703. const path = String(cookie?.path || '/').startsWith('/')
  6704. ? String(cookie?.path || '/')
  6705. : `/${String(cookie?.path || '')}`;
  6706. return `https://${host}${path}`;
  6707. }
  6708. async function collectCookiesForPreLoginCleanup() {
  6709. if (!chrome.cookies?.getAll) {
  6710. return [];
  6711. }
  6712. const stores = chrome.cookies.getAllCookieStores
  6713. ? await chrome.cookies.getAllCookieStores()
  6714. : [{ id: undefined }];
  6715. const cookies = [];
  6716. const seen = new Set();
  6717. for (const store of stores) {
  6718. const storeId = store?.id;
  6719. const batch = await chrome.cookies.getAll(storeId ? { storeId } : {});
  6720. for (const cookie of batch || []) {
  6721. if (!shouldClearPreLoginCookie(cookie)) continue;
  6722. const key = [
  6723. cookie.storeId || storeId || '',
  6724. cookie.domain || '',
  6725. cookie.path || '',
  6726. cookie.name || '',
  6727. cookie.partitionKey ? JSON.stringify(cookie.partitionKey) : '',
  6728. ].join('|');
  6729. if (seen.has(key)) continue;
  6730. seen.add(key);
  6731. cookies.push(cookie);
  6732. }
  6733. }
  6734. return cookies;
  6735. }
  6736. async function removeCookieDirectly(cookie) {
  6737. const details = {
  6738. url: buildCookieRemovalUrl(cookie),
  6739. name: cookie.name,
  6740. };
  6741. if (cookie.storeId) {
  6742. details.storeId = cookie.storeId;
  6743. }
  6744. if (cookie.partitionKey) {
  6745. details.partitionKey = cookie.partitionKey;
  6746. }
  6747. try {
  6748. const result = await chrome.cookies.remove(details);
  6749. return Boolean(result);
  6750. } catch (err) {
  6751. console.warn(LOG_PREFIX, '[removeCookieDirectly] failed', {
  6752. domain: cookie?.domain,
  6753. name: cookie?.name,
  6754. message: getErrorMessage(err),
  6755. });
  6756. return false;
  6757. }
  6758. }
  6759. async function runPreStep6CookieCleanup() {
  6760. await addLog(
  6761. `步骤 6:开始前等待 ${Math.round(STEP6_PRE_LOGIN_COOKIE_CLEAR_DELAY_MS / 1000)} 秒,然后直接删除 ChatGPT / OpenAI cookies...`,
  6762. 'info'
  6763. );
  6764. await sleepWithStop(STEP6_PRE_LOGIN_COOKIE_CLEAR_DELAY_MS);
  6765. if (!chrome.cookies?.getAll || !chrome.cookies?.remove) {
  6766. await addLog('步骤 6:当前浏览器不支持 cookies API,无法直接删除 cookies。', 'warn');
  6767. return;
  6768. }
  6769. const cookies = await collectCookiesForPreLoginCleanup();
  6770. let removedCount = 0;
  6771. for (const cookie of cookies) {
  6772. throwIfStopped();
  6773. if (await removeCookieDirectly(cookie)) {
  6774. removedCount += 1;
  6775. }
  6776. }
  6777. if (chrome.browsingData?.removeCookies) {
  6778. try {
  6779. await chrome.browsingData.removeCookies({
  6780. since: 0,
  6781. origins: PRE_LOGIN_COOKIE_CLEAR_ORIGINS,
  6782. });
  6783. } catch (err) {
  6784. await addLog(`步骤 6:browsingData 补扫 cookies 失败:${getErrorMessage(err)}`, 'warn');
  6785. }
  6786. }
  6787. await addLog(`步骤 6:已直接删除 ${removedCount} 个 ChatGPT / OpenAI cookies,准备继续获取链接并登录。`, 'ok');
  6788. }
  6789. // ============================================================
  6790. // Step 6: Login and ensure the auth page reaches the login verification page
  6791. // ============================================================
  6792. async function refreshOAuthUrlBeforeStep6(state) {
  6793. await addLog(`步骤 6:正在刷新登录用的 ${getPanelModeLabel(state)} OAuth 链接...`);
  6794. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] requesting fresh OAuth directly from panel');
  6795. const refreshResult = await requestOAuthUrlFromPanel(state, { logLabel: '步骤 6' });
  6796. await handleStepData(1, refreshResult);
  6797. if (!refreshResult?.oauthUrl) {
  6798. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  6799. }
  6800. return refreshResult.oauthUrl;
  6801. }
  6802. function isStep6SuccessResult(result) {
  6803. return result?.step6Outcome === 'success';
  6804. }
  6805. function isStep6RecoverableResult(result) {
  6806. return result?.step6Outcome === 'recoverable';
  6807. }
  6808. async function getLoginAuthStateFromContent() {
  6809. const result = await sendToContentScriptResilient(
  6810. 'signup-page',
  6811. {
  6812. type: 'GET_LOGIN_AUTH_STATE',
  6813. source: 'background',
  6814. payload: {},
  6815. },
  6816. {
  6817. timeoutMs: 15000,
  6818. retryDelayMs: 600,
  6819. logMessage: '步骤 7:认证页正在切换,等待页面重新就绪后继续确认验证码页状态...',
  6820. }
  6821. );
  6822. if (result?.error) {
  6823. throw new Error(result.error);
  6824. }
  6825. return result || {};
  6826. }
  6827. async function ensureStep7VerificationPageReady() {
  6828. const pageState = await getLoginAuthStateFromContent();
  6829. if (pageState.state === 'verification_page') {
  6830. return pageState;
  6831. }
  6832. const stateLabel = getLoginAuthStateLabel(pageState.state);
  6833. const urlPart = pageState.url ? ` URL: ${pageState.url}` : '';
  6834. throw new Error(`当前未进入登录验证码页面,请先重新完成步骤 6。当前状态:${stateLabel}.${urlPart}`.trim());
  6835. }
  6836. async function skipLoginVerificationStepsForCpaCallback() {
  6837. await setState({
  6838. lastLoginCode: null,
  6839. loginVerificationRequestedAt: null,
  6840. });
  6841. await setStepStatus(6, 'skipped');
  6842. await addLog('步骤 6:当前已选择“第六步回调”,直接跳过步骤 6、7。', 'warn');
  6843. const latestState = await getState();
  6844. if (!isStepDoneStatus(latestState.stepStatuses?.[7])) {
  6845. await setStepStatus(7, 'skipped');
  6846. await addLog('步骤 7:当前已选择“第六步回调”,本轮无需获取登录验证码。', 'warn');
  6847. }
  6848. }
  6849. async function executeStep6(state) {
  6850. if (shouldSkipLoginVerificationForCpaCallback(state)) {
  6851. await skipLoginVerificationStepsForCpaCallback();
  6852. return;
  6853. }
  6854. if (!state.email) {
  6855. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  6856. }
  6857. await runPreStep6CookieCleanup();
  6858. let attempt = 0;
  6859. while (true) {
  6860. throwIfStopped();
  6861. attempt += 1;
  6862. const currentState = attempt === 1 ? state : await getState();
  6863. const password = currentState.password || currentState.customPassword || '';
  6864. const oauthUrl = await refreshOAuthUrlBeforeStep6(currentState);
  6865. if (attempt === 1) {
  6866. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  6867. } else {
  6868. await addLog(`步骤 6:上一轮登录未进入验证码页,正在重新发起第 ${attempt} 轮登录尝试...`, 'warn');
  6869. }
  6870. await reuseOrCreateTab('signup-page', oauthUrl);
  6871. const result = await sendToContentScriptResilient(
  6872. 'signup-page',
  6873. {
  6874. type: 'EXECUTE_STEP',
  6875. step: 6,
  6876. source: 'background',
  6877. payload: {
  6878. email: currentState.email,
  6879. password,
  6880. },
  6881. },
  6882. {
  6883. timeoutMs: 180000,
  6884. retryDelayMs: 700,
  6885. logMessage: '步骤 6:认证页正在切换,等待页面重新就绪后继续登录...',
  6886. }
  6887. );
  6888. if (result?.error) {
  6889. throw new Error(result.error);
  6890. }
  6891. if (isStep6SuccessResult(result)) {
  6892. await completeStepFromBackground(6, {
  6893. loginVerificationRequestedAt: result.loginVerificationRequestedAt || null,
  6894. });
  6895. return;
  6896. }
  6897. if (isStep6RecoverableResult(result)) {
  6898. const reasonMessage = result.message
  6899. || `当前停留在${getLoginAuthStateLabel(result.state)},准备重新执行步骤 6。`;
  6900. await addLog(`步骤 6:${reasonMessage}`, 'warn');
  6901. continue;
  6902. }
  6903. throw new Error('步骤 6:认证页未返回可识别的登录结果。');
  6904. }
  6905. }
  6906. // ============================================================
  6907. // Step 7: Poll login verification mail and submit the login code
  6908. // ============================================================
  6909. async function runStep7Attempt(state) {
  6910. const mail = getMailConfig(state);
  6911. if (mail.error) throw new Error(mail.error);
  6912. const stepStartedAt = Date.now();
  6913. const authTabId = await getTabId('signup-page');
  6914. if (authTabId) {
  6915. await chrome.tabs.update(authTabId, { active: true });
  6916. } else {
  6917. if (!state.oauthUrl) {
  6918. throw new Error('缺少登录用 OAuth 链接,请先完成步骤 6。');
  6919. }
  6920. await reuseOrCreateTab('signup-page', state.oauthUrl);
  6921. }
  6922. throwIfStopped();
  6923. await ensureStep7VerificationPageReady();
  6924. await addLog('步骤 7:登录验证码页面已就绪,开始获取验证码。', 'info');
  6925. if (shouldUseCustomRegistrationEmail(state)) {
  6926. await confirmCustomVerificationStepBypass(7);
  6927. return;
  6928. }
  6929. throwIfStopped();
  6930. if (mail.provider === HOTMAIL_PROVIDER || mail.provider === LUCKMAIL_PROVIDER || mail.provider === CLOUDFLARE_TEMP_EMAIL_PROVIDER) {
  6931. await addLog(`步骤 7:正在通过 ${mail.label} 轮询验证码...`);
  6932. } else {
  6933. await addLog(`步骤 7:正在打开${mail.label}...`);
  6934. const alive = await isTabAlive(mail.source);
  6935. if (alive) {
  6936. if (mail.navigateOnReuse) {
  6937. await reuseOrCreateTab(mail.source, mail.url, {
  6938. inject: mail.inject,
  6939. injectSource: mail.injectSource,
  6940. });
  6941. } else {
  6942. const tabId = await getTabId(mail.source);
  6943. await chrome.tabs.update(tabId, { active: true });
  6944. }
  6945. } else {
  6946. await reuseOrCreateTab(mail.source, mail.url, {
  6947. inject: mail.inject,
  6948. injectSource: mail.injectSource,
  6949. });
  6950. }
  6951. }
  6952. await resolveVerificationStep(7, state, mail, {
  6953. filterAfterTimestamp: mail.provider === HOTMAIL_PROVIDER ? undefined : Math.max(0, stepStartedAt - 60000),
  6954. requestFreshCodeFirst: false,
  6955. resendIntervalMs: mail.provider === HOTMAIL_PROVIDER ? 0 : STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS,
  6956. });
  6957. }
  6958. async function rerunStep6ForStep7Recovery() {
  6959. const currentState = await getState();
  6960. await addLog('步骤 7:正在回到步骤 6,重新发起登录验证码流程...', 'warn');
  6961. await executeStep6(currentState);
  6962. await sleepWithStop(3000);
  6963. }
  6964. async function executeStep7(state) {
  6965. if (shouldSkipLoginVerificationForCpaCallback(state)) {
  6966. await setState({
  6967. lastLoginCode: null,
  6968. loginVerificationRequestedAt: null,
  6969. });
  6970. await setStepStatus(7, 'skipped');
  6971. await addLog('步骤 7:当前已选择“第六步回调”,本轮无需获取登录验证码。', 'warn');
  6972. return;
  6973. }
  6974. let currentState = state;
  6975. let mailPollingAttempt = 1;
  6976. let lastMailPollingError = null;
  6977. while (true) {
  6978. try {
  6979. await runStep7Attempt(currentState);
  6980. return;
  6981. } catch (err) {
  6982. if (!isVerificationMailPollingError(err)) {
  6983. throw err;
  6984. }
  6985. lastMailPollingError = err;
  6986. if (mailPollingAttempt >= STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS) {
  6987. break;
  6988. }
  6989. mailPollingAttempt += 1;
  6990. await addLog(
  6991. `步骤 7:检测到邮箱轮询类失败,准备从步骤 6 重新开始(${mailPollingAttempt}/${STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS})...`,
  6992. 'warn'
  6993. );
  6994. await rerunStep6ForStep7Recovery();
  6995. currentState = await getState();
  6996. }
  6997. }
  6998. if (lastMailPollingError) {
  6999. throw new Error(
  7000. `步骤 7:登录验证码流程在 ${STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS} 轮邮箱轮询恢复后仍未成功。最后一次原因:${lastMailPollingError.message}`
  7001. );
  7002. }
  7003. throw new Error('步骤 7:登录验证码流程未成功完成。');
  7004. }
  7005. // ============================================================
  7006. // Step 8: 完成 OAuth(自动点击 + localhost 回调监听)
  7007. // ============================================================
  7008. let webNavListener = null;
  7009. let webNavCommittedListener = null;
  7010. let step8TabUpdatedListener = null;
  7011. let step8PendingReject = null;
  7012. const STEP8_CLICK_EFFECT_TIMEOUT_MS = 15000;
  7013. const STEP8_CLICK_RETRY_DELAY_MS = 500;
  7014. const STEP8_READY_WAIT_TIMEOUT_MS = 30000;
  7015. const STEP8_MAX_ROUNDS = 5;
  7016. const STEP8_STRATEGIES = [
  7017. { mode: 'content', strategy: 'requestSubmit', label: 'form.requestSubmit' },
  7018. { mode: 'debugger', label: 'debugger click' },
  7019. { mode: 'content', strategy: 'nativeClick', label: 'element.click' },
  7020. { mode: 'content', strategy: 'dispatchClick', label: 'dispatch click' },
  7021. { mode: 'debugger', label: 'debugger click retry' },
  7022. ];
  7023. function cleanupStep8NavigationListeners() {
  7024. if (webNavListener) {
  7025. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  7026. webNavListener = null;
  7027. }
  7028. if (webNavCommittedListener) {
  7029. chrome.webNavigation.onCommitted.removeListener(webNavCommittedListener);
  7030. webNavCommittedListener = null;
  7031. }
  7032. if (step8TabUpdatedListener) {
  7033. chrome.tabs.onUpdated.removeListener(step8TabUpdatedListener);
  7034. step8TabUpdatedListener = null;
  7035. }
  7036. }
  7037. function rejectPendingStep8(error) {
  7038. if (!step8PendingReject) return;
  7039. const reject = step8PendingReject;
  7040. step8PendingReject = null;
  7041. reject(error);
  7042. }
  7043. function throwIfStep8SettledOrStopped(isSettled = false) {
  7044. if (isSettled || stopRequested) {
  7045. throw new Error(STOP_ERROR_MESSAGE);
  7046. }
  7047. }
  7048. async function ensureStep8SignupPageReady(tabId, options = {}) {
  7049. await ensureContentScriptReadyOnTab('signup-page', tabId, {
  7050. inject: SIGNUP_PAGE_INJECT_FILES,
  7051. injectSource: 'signup-page',
  7052. timeoutMs: options.timeoutMs ?? 15000,
  7053. retryDelayMs: options.retryDelayMs ?? 600,
  7054. logMessage: options.logMessage || '',
  7055. });
  7056. }
  7057. async function getStep8PageState(tabId, responseTimeoutMs = 1500) {
  7058. try {
  7059. const result = await sendTabMessageWithTimeout(tabId, 'signup-page', {
  7060. type: 'STEP8_GET_STATE',
  7061. source: 'background',
  7062. payload: {},
  7063. }, responseTimeoutMs);
  7064. if (result?.error) {
  7065. throw new Error(result.error);
  7066. }
  7067. return result;
  7068. } catch (err) {
  7069. if (isRetryableContentScriptTransportError(err)) {
  7070. return null;
  7071. }
  7072. throw err;
  7073. }
  7074. }
  7075. async function waitForStep8Ready(tabId, timeoutMs = STEP8_READY_WAIT_TIMEOUT_MS) {
  7076. const start = Date.now();
  7077. let recovered = false;
  7078. while (Date.now() - start < timeoutMs) {
  7079. throwIfStopped();
  7080. const pageState = await getStep8PageState(tabId);
  7081. if (pageState?.addPhonePage) {
  7082. throw new Error('步骤 8:认证页进入了手机号页面,当前不是 OAuth 同意页,无法继续自动授权。');
  7083. }
  7084. if (pageState?.consentReady) {
  7085. return pageState;
  7086. }
  7087. if (pageState === null && !recovered) {
  7088. recovered = true;
  7089. await ensureStep8SignupPageReady(tabId, {
  7090. timeoutMs: Math.min(10000, timeoutMs),
  7091. logMessage: '步骤 8:认证页内容脚本已失联,正在等待页面重新就绪...',
  7092. });
  7093. continue;
  7094. }
  7095. recovered = false;
  7096. await sleepWithStop(250);
  7097. }
  7098. throw new Error('步骤 8:长时间未进入 OAuth 同意页,无法定位“继续”按钮。');
  7099. }
  7100. async function prepareStep8DebuggerClick(tabId) {
  7101. await ensureStep8SignupPageReady(tabId, {
  7102. timeoutMs: 15000,
  7103. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续定位按钮...',
  7104. });
  7105. const result = await sendToContentScriptResilient('signup-page', {
  7106. type: 'STEP8_FIND_AND_CLICK',
  7107. source: 'background',
  7108. payload: {},
  7109. }, {
  7110. timeoutMs: 15000,
  7111. retryDelayMs: 600,
  7112. logMessage: '步骤 8:认证页正在切换,等待 OAuth 同意页按钮重新就绪...',
  7113. });
  7114. if (result?.error) {
  7115. throw new Error(result.error);
  7116. }
  7117. return result;
  7118. }
  7119. async function triggerStep8ContentStrategy(tabId, strategy) {
  7120. await ensureStep8SignupPageReady(tabId, {
  7121. timeoutMs: 15000,
  7122. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续点击“继续”按钮...',
  7123. });
  7124. const result = await sendToContentScriptResilient('signup-page', {
  7125. type: 'STEP8_TRIGGER_CONTINUE',
  7126. source: 'background',
  7127. payload: {
  7128. strategy,
  7129. findTimeoutMs: 4000,
  7130. enabledTimeoutMs: 3000,
  7131. },
  7132. }, {
  7133. timeoutMs: 15000,
  7134. retryDelayMs: 600,
  7135. logMessage: '步骤 8:认证页正在切换,等待“继续”按钮重新就绪...',
  7136. });
  7137. if (result?.error) {
  7138. throw new Error(result.error);
  7139. }
  7140. return result;
  7141. }
  7142. async function reloadStep8ConsentPage(tabId, timeoutMs = 30000) {
  7143. if (!Number.isInteger(tabId)) {
  7144. throw new Error('步骤 8:缺少有效的认证页标签页,无法刷新后重试。');
  7145. }
  7146. await chrome.tabs.update(tabId, { active: true }).catch(() => { });
  7147. await new Promise((resolve, reject) => {
  7148. let settled = false;
  7149. const timer = setTimeout(() => {
  7150. if (settled) return;
  7151. settled = true;
  7152. chrome.tabs.onUpdated.removeListener(listener);
  7153. reject(new Error('步骤 8:刷新认证页后等待页面完成加载超时。'));
  7154. }, timeoutMs);
  7155. const listener = (updatedTabId, changeInfo) => {
  7156. if (updatedTabId !== tabId) return;
  7157. if (changeInfo.status !== 'complete') return;
  7158. if (settled) return;
  7159. settled = true;
  7160. clearTimeout(timer);
  7161. chrome.tabs.onUpdated.removeListener(listener);
  7162. resolve();
  7163. };
  7164. chrome.tabs.onUpdated.addListener(listener);
  7165. chrome.tabs.reload(tabId, { bypassCache: false }).catch((err) => {
  7166. if (settled) return;
  7167. settled = true;
  7168. clearTimeout(timer);
  7169. chrome.tabs.onUpdated.removeListener(listener);
  7170. reject(err);
  7171. });
  7172. });
  7173. await ensureStep8SignupPageReady(tabId, {
  7174. timeoutMs: Math.min(15000, timeoutMs),
  7175. logMessage: '步骤 8:认证页刷新后内容脚本尚未就绪,正在等待页面恢复...',
  7176. });
  7177. }
  7178. async function waitForStep8ClickEffect(tabId, baselineUrl, timeoutMs = STEP8_CLICK_EFFECT_TIMEOUT_MS) {
  7179. const start = Date.now();
  7180. let recovered = false;
  7181. while (Date.now() - start < timeoutMs) {
  7182. throwIfStopped();
  7183. const tab = await chrome.tabs.get(tabId).catch(() => null);
  7184. if (!tab) {
  7185. throw new Error('步骤 8:认证页面标签页已关闭,无法继续自动授权。');
  7186. }
  7187. if (baselineUrl && typeof tab.url === 'string' && tab.url !== baselineUrl) {
  7188. return { progressed: true, reason: 'url_changed', url: tab.url };
  7189. }
  7190. const pageState = await getStep8PageState(tabId);
  7191. if (pageState?.addPhonePage) {
  7192. throw new Error('步骤 8:点击“继续”后页面跳到了手机号页面,当前流程无法继续自动授权。');
  7193. }
  7194. if (pageState === null) {
  7195. if (!recovered) {
  7196. recovered = true;
  7197. await ensureStep8SignupPageReady(tabId, {
  7198. timeoutMs: Math.max(3000, Math.min(8000, timeoutMs)),
  7199. logMessage: '步骤 8:点击后认证页正在重载,正在等待内容脚本重新就绪...',
  7200. }).catch(() => null);
  7201. continue;
  7202. }
  7203. await sleepWithStop(200);
  7204. continue;
  7205. }
  7206. recovered = false;
  7207. await sleepWithStop(200);
  7208. }
  7209. return { progressed: false, reason: 'no_effect' };
  7210. }
  7211. function getStep8EffectLabel(effect) {
  7212. switch (effect?.reason) {
  7213. case 'url_changed':
  7214. return `URL 已变化:${effect.url}`;
  7215. case 'page_reloading':
  7216. return '页面正在跳转或重载';
  7217. case 'left_consent_page':
  7218. return `页面已离开 OAuth 同意页:${effect.url || 'unknown'}`;
  7219. default:
  7220. return '页面仍停留在 OAuth 同意页';
  7221. }
  7222. }
  7223. async function executeStep8(state) {
  7224. if (!state.oauthUrl) {
  7225. throw new Error('缺少登录用 OAuth 链接,请先完成步骤 6。');
  7226. }
  7227. await addLog('步骤 8:正在监听 localhost 回调地址...');
  7228. return new Promise((resolve, reject) => {
  7229. let resolved = false;
  7230. let signupTabId = null;
  7231. const cleanupListener = () => {
  7232. cleanupStep8NavigationListeners();
  7233. step8PendingReject = null;
  7234. };
  7235. const rejectStep8 = (error) => {
  7236. if (resolved) return;
  7237. resolved = true;
  7238. clearTimeout(timeout);
  7239. cleanupListener();
  7240. reject(error);
  7241. };
  7242. const finalizeStep8Callback = (callbackUrl) => {
  7243. if (resolved || !callbackUrl) return;
  7244. resolved = true;
  7245. cleanupListener();
  7246. clearTimeout(timeout);
  7247. addLog(`步骤 8:已捕获 localhost 地址:${callbackUrl}`, 'ok').then(() => {
  7248. return completeStepFromBackground(8, { localhostUrl: callbackUrl });
  7249. }).then(() => {
  7250. resolve();
  7251. }).catch((err) => {
  7252. reject(err);
  7253. });
  7254. };
  7255. const timeout = setTimeout(() => {
  7256. rejectStep8(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  7257. }, 120000);
  7258. step8PendingReject = (error) => {
  7259. rejectStep8(error);
  7260. };
  7261. webNavListener = (details) => {
  7262. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  7263. finalizeStep8Callback(callbackUrl);
  7264. };
  7265. webNavCommittedListener = (details) => {
  7266. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  7267. finalizeStep8Callback(callbackUrl);
  7268. };
  7269. step8TabUpdatedListener = (tabId, changeInfo, tab) => {
  7270. const callbackUrl = getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId);
  7271. finalizeStep8Callback(callbackUrl);
  7272. };
  7273. (async () => {
  7274. try {
  7275. throwIfStep8SettledOrStopped(resolved);
  7276. signupTabId = await getTabId('signup-page');
  7277. throwIfStep8SettledOrStopped(resolved);
  7278. if (signupTabId && await isTabAlive('signup-page')) {
  7279. await chrome.tabs.update(signupTabId, { active: true });
  7280. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  7281. } else {
  7282. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  7283. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  7284. }
  7285. throwIfStep8SettledOrStopped(resolved);
  7286. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  7287. chrome.webNavigation.onCommitted.addListener(webNavCommittedListener);
  7288. chrome.tabs.onUpdated.addListener(step8TabUpdatedListener);
  7289. await ensureStep8SignupPageReady(signupTabId, {
  7290. timeoutMs: 15000,
  7291. logMessage: '步骤 8:认证页内容脚本尚未就绪,正在等待页面恢复...',
  7292. });
  7293. for (let round = 1; round <= STEP8_MAX_ROUNDS && !resolved; round++) {
  7294. throwIfStep8SettledOrStopped(resolved);
  7295. const pageState = await waitForStep8Ready(signupTabId);
  7296. if (!pageState?.consentReady) {
  7297. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  7298. continue;
  7299. }
  7300. const strategy = STEP8_STRATEGIES[Math.min(round - 1, STEP8_STRATEGIES.length - 1)];
  7301. await addLog(`步骤 8:第 ${round}/${STEP8_MAX_ROUNDS} 轮尝试点击“继续”(${strategy.label})...`);
  7302. if (strategy.mode === 'debugger') {
  7303. const clickTarget = await prepareStep8DebuggerClick(signupTabId);
  7304. throwIfStep8SettledOrStopped(resolved);
  7305. await clickWithDebugger(signupTabId, clickTarget?.rect);
  7306. } else {
  7307. await triggerStep8ContentStrategy(signupTabId, strategy.strategy);
  7308. }
  7309. if (resolved) {
  7310. return;
  7311. }
  7312. const effect = await waitForStep8ClickEffect(signupTabId, pageState.url);
  7313. if (resolved) {
  7314. return;
  7315. }
  7316. if (effect.progressed) {
  7317. await addLog(`步骤 8:检测到本次点击已生效,${getStep8EffectLabel(effect)},继续等待 localhost 回调...`, 'info');
  7318. break;
  7319. }
  7320. if (round >= STEP8_MAX_ROUNDS) {
  7321. throw new Error(`步骤 8:连续 ${STEP8_MAX_ROUNDS} 轮点击“继续”后页面仍无反应。`);
  7322. }
  7323. await addLog(`步骤 8:${strategy.label} 本轮点击后页面无反应,正在刷新认证页后重试(下一轮 ${round + 1}/${STEP8_MAX_ROUNDS})...`, 'warn');
  7324. await reloadStep8ConsentPage(signupTabId);
  7325. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  7326. }
  7327. } catch (err) {
  7328. rejectStep8(err);
  7329. }
  7330. })();
  7331. });
  7332. }
  7333. // ============================================================
  7334. // Step 9: 平台回调验证
  7335. // ============================================================
  7336. async function executeStep9(state) {
  7337. if (getPanelMode(state) === 'sub2api') {
  7338. return executeSub2ApiStep9(state);
  7339. }
  7340. return executeCpaStep9(state);
  7341. }
  7342. async function executeCpaStep9(state) {
  7343. if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
  7344. throw new Error('步骤 8 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 8。');
  7345. }
  7346. if (!state.localhostUrl) {
  7347. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  7348. }
  7349. if (!state.vpsUrl) {
  7350. throw new Error('尚未填写 CPA 地址,请先在侧边栏输入。');
  7351. }
  7352. if (shouldBypassStep9ForLocalCpa(state)) {
  7353. await addLog('步骤 9:检测到本地 CPA,且当前策略为“跳过第9步”,本轮不再重复提交回调地址。', 'info');
  7354. await completeStepFromBackground(9, {
  7355. localhostUrl: state.localhostUrl,
  7356. verifiedStatus: 'local-auto',
  7357. });
  7358. return;
  7359. }
  7360. await addLog('步骤 9:正在打开 CPA 面板...');
  7361. const injectFiles = ['content/activation-utils.js', 'content/utils.js', 'content/vps-panel.js'];
  7362. let tabId = await getTabId('vps-panel');
  7363. const alive = tabId && await isTabAlive('vps-panel');
  7364. if (!alive) {
  7365. tabId = await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  7366. inject: injectFiles,
  7367. reloadIfSameUrl: true,
  7368. });
  7369. } else {
  7370. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  7371. await chrome.tabs.update(tabId, { active: true });
  7372. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  7373. }
  7374. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  7375. inject: injectFiles,
  7376. timeoutMs: 45000,
  7377. retryDelayMs: 900,
  7378. logMessage: '步骤 9:CPA 面板仍在加载,正在重试连接...',
  7379. });
  7380. await addLog('步骤 9:正在填写回调地址...');
  7381. const result = await sendToContentScriptResilient('vps-panel', {
  7382. type: 'EXECUTE_STEP',
  7383. step: 9,
  7384. source: 'background',
  7385. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  7386. }, {
  7387. timeoutMs: 30000,
  7388. retryDelayMs: 700,
  7389. logMessage: '步骤 9:CPA 面板通信未就绪,正在等待页面恢复...',
  7390. });
  7391. if (result?.error) {
  7392. throw new Error(result.error);
  7393. }
  7394. }
  7395. async function executeSub2ApiStep9(state) {
  7396. if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
  7397. throw new Error('步骤 8 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 8。');
  7398. }
  7399. if (!state.localhostUrl) {
  7400. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  7401. }
  7402. if (!state.sub2apiSessionId) {
  7403. throw new Error('缺少 SUB2API 会话信息,请重新执行步骤 1。');
  7404. }
  7405. if (!state.sub2apiEmail) {
  7406. throw new Error('尚未配置 SUB2API 登录邮箱,请先在侧边栏填写。');
  7407. }
  7408. if (!state.sub2apiPassword) {
  7409. throw new Error('尚未配置 SUB2API 登录密码,请先在侧边栏填写。');
  7410. }
  7411. const sub2apiUrl = normalizeSub2ApiUrl(state.sub2apiUrl);
  7412. const injectFiles = ['content/utils.js', 'content/sub2api-panel.js'];
  7413. await addLog('步骤 9:正在打开 SUB2API 后台...');
  7414. let tabId = await getTabId('sub2api-panel');
  7415. const alive = tabId && await isTabAlive('sub2api-panel');
  7416. if (!alive) {
  7417. tabId = await reuseOrCreateTab('sub2api-panel', sub2apiUrl, {
  7418. inject: injectFiles,
  7419. injectSource: 'sub2api-panel',
  7420. reloadIfSameUrl: true,
  7421. });
  7422. } else {
  7423. await closeConflictingTabsForSource('sub2api-panel', sub2apiUrl, { excludeTabIds: [tabId] });
  7424. await chrome.tabs.update(tabId, { active: true });
  7425. await rememberSourceLastUrl('sub2api-panel', sub2apiUrl);
  7426. }
  7427. await ensureContentScriptReadyOnTab('sub2api-panel', tabId, {
  7428. inject: injectFiles,
  7429. injectSource: 'sub2api-panel',
  7430. });
  7431. await addLog('步骤 9:正在向 SUB2API 提交回调并创建账号...');
  7432. const result = await sendToContentScript('sub2api-panel', {
  7433. type: 'EXECUTE_STEP',
  7434. step: 9,
  7435. source: 'background',
  7436. payload: {
  7437. localhostUrl: state.localhostUrl,
  7438. sub2apiUrl,
  7439. sub2apiEmail: state.sub2apiEmail,
  7440. sub2apiPassword: state.sub2apiPassword,
  7441. sub2apiGroupName: state.sub2apiGroupName,
  7442. sub2apiSessionId: state.sub2apiSessionId,
  7443. sub2apiOAuthState: state.sub2apiOAuthState,
  7444. sub2apiGroupId: state.sub2apiGroupId,
  7445. sub2apiDraftName: state.sub2apiDraftName,
  7446. },
  7447. }, {
  7448. responseTimeoutMs: SUB2API_STEP9_RESPONSE_TIMEOUT_MS,
  7449. });
  7450. if (result?.error) {
  7451. throw new Error(result.error);
  7452. }
  7453. }
  7454. // ============================================================
  7455. // Open Side Panel on extension icon click
  7456. // ============================================================
  7457. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
  7458. chrome.alarms.onAlarm.addListener((alarm) => {
  7459. if (alarm.name !== AUTO_RUN_TIMER_ALARM_NAME) {
  7460. return;
  7461. }
  7462. launchAutoRunTimerPlan('alarm').catch((err) => {
  7463. console.error(LOG_PREFIX, 'Failed to resume auto run from timer alarm:', err);
  7464. });
  7465. });
  7466. chrome.runtime.onStartup.addListener(() => {
  7467. restoreAutoRunTimerIfNeeded().catch((err) => {
  7468. console.error(LOG_PREFIX, 'Failed to restore auto run timer on startup:', err);
  7469. });
  7470. });
  7471. chrome.runtime.onInstalled.addListener(() => {
  7472. restoreAutoRunTimerIfNeeded().catch((err) => {
  7473. console.error(LOG_PREFIX, 'Failed to restore auto run timer on install/update:', err);
  7474. });
  7475. });
  7476. restoreAutoRunTimerIfNeeded().catch((err) => {
  7477. console.error(LOG_PREFIX, 'Failed to restore auto run timer:', err);
  7478. });