background.js 232 KB

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