background.js 264 KB

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