background.js 276 KB

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