background.js 281 KB

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