background.js 276 KB

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