background.js 235 KB

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