background.js 247 KB

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