background.js 266 KB

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