background.js 235 KB

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