background.js 194 KB

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