background.js 230 KB

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