background.js 207 KB

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