background.js 267 KB

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