background.js 211 KB

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