background.js 196 KB

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