background.js 252 KB

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