background.js 209 KB

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