background.js 231 KB

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