background.js 233 KB

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