background.js 179 KB

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