background.js 212 KB

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