background.js 187 KB

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