background.js 277 KB

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