background.js 153 KB

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