background.js 210 KB

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