background.js 192 KB

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