background.js 267 KB

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