background.js 241 KB

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