background.js 236 KB

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