background.js 212 KB

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