background.js 193 KB

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