background.js 235 KB

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