background.js 225 KB

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