background.js 230 KB

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