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