background.js 194 KB

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