background.js 222 KB

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