background.js 165 KB

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