background.js 185 KB

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