background.js 260 KB

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