background.js 235 KB

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