background.js 224 KB

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