background.js 268 KB

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