background.js 228 KB

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