setting.go 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  1. package service
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "os"
  10. "reflect"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/google/uuid"
  16. "github.com/xlzd/gotp"
  17. "gorm.io/gorm"
  18. "github.com/mhsanaei/3x-ui/v3/internal/config"
  19. "github.com/mhsanaei/3x-ui/v3/internal/database"
  20. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  21. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  22. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  23. "github.com/mhsanaei/3x-ui/v3/internal/util/netproxy"
  24. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  25. "github.com/mhsanaei/3x-ui/v3/internal/util/reflect_util"
  26. "github.com/mhsanaei/3x-ui/v3/internal/web/entity"
  27. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  28. )
  29. //go:embed config.json
  30. var xrayTemplateConfig string
  31. const (
  32. DefaultSubClashUserAgentRegex = `(?i)(clash|mihomo)`
  33. DefaultSubJsonUserAgentRegex = ``
  34. DefaultRemarkTemplate = "{{INBOUND}}-{{EMAIL}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D"
  35. DefaultSubExpiredTemplate = "⛔ {{EMAIL}} | Expired: {{EXPIRE_DATE}}"
  36. DefaultSubTrafficDepletedTemplate = "🚫 {{EMAIL}} | Traffic Depleted | {{TRAFFIC_USED}}/{{TRAFFIC_TOTAL}}"
  37. DefaultTrustedProxyCIDRs = "127.0.0.1/32,::1/128"
  38. maxRegexLength = 2048
  39. )
  40. var defaultValueMap = map[string]string{
  41. "xrayTemplateConfig": xrayTemplateConfig,
  42. "webListen": "",
  43. "webDomain": "",
  44. "webPort": "2053",
  45. "webCertFile": "",
  46. "webKeyFile": "",
  47. "secret": random.Seq(32),
  48. "panelGuid": uuid.NewString(),
  49. "apiToken": "",
  50. // Node mTLS material (opt-in). All default empty: the CA + master client
  51. // cert are minted lazily on first use, and the node-side trust CA is pasted
  52. // in by the operator. Kept out of entity.AllSetting so private keys never
  53. // reach the settings UI/export.
  54. "nodeMtlsCaCertPem": "",
  55. "nodeMtlsCaKeyPem": "",
  56. "nodeMtlsClientCertPem": "",
  57. "nodeMtlsClientKeyPem": "",
  58. "nodeMtlsClientCertSha256": "",
  59. "nodeMtlsClientCAPem": "",
  60. "webBasePath": normalizeBasePath(getEnv("XUI_INIT_WEB_BASE_PATH", "/")),
  61. "sessionMaxAge": "360",
  62. "trustedProxyCIDRs": DefaultTrustedProxyCIDRs,
  63. "ipLimitAllowlist": "",
  64. "pageSize": "25",
  65. "expireDiff": "0",
  66. "trafficDiff": "0",
  67. "remarkTemplate": DefaultRemarkTemplate,
  68. "subShowIdentityOnAllLinks": "false",
  69. "subInfoNodeEnable": "false",
  70. "subExpiredTemplate": DefaultSubExpiredTemplate,
  71. "subTrafficDepletedTemplate": DefaultSubTrafficDepletedTemplate,
  72. "timeLocation": "Local",
  73. "tgBotEnable": "false",
  74. "tgBotToken": "",
  75. "tgBotProxy": "",
  76. "tgBotAPIServer": "",
  77. "tgBotChatId": "",
  78. "tgRunTime": "@daily",
  79. "tgBotBackup": "false",
  80. "tgCpu": "80",
  81. "tgMemory": "80",
  82. "tgLang": "en-US",
  83. "twoFactorEnable": "false",
  84. "twoFactorToken": "",
  85. "subEnable": "true",
  86. "subJsonEnable": "false",
  87. "subJsonAutoDetect": "false",
  88. "subJsonAlwaysArray": "false",
  89. "subJsonUserAgentRegex": "",
  90. "subClashAutoDetect": "false",
  91. "subClashUserAgentRegex": "",
  92. "subTitle": "",
  93. "subSupportUrl": "",
  94. "subProfileUrl": "",
  95. "subAnnounce": "",
  96. "subEnableRouting": "false",
  97. "subRoutingRules": "",
  98. "subHideSettings": "false",
  99. "subIncyEnableRouting": "false",
  100. "subIncyRoutingRules": "",
  101. "subListen": "",
  102. "subPort": "2096",
  103. "subPath": "/sub/",
  104. "subDomain": "",
  105. "subCertFile": "",
  106. "subKeyFile": "",
  107. "subUpdates": "12",
  108. "subEncrypt": "true",
  109. "subURI": "",
  110. "subJsonPath": "/json/",
  111. "subJsonURI": "",
  112. "subClashEnable": "false",
  113. "subClashPath": "/clash/",
  114. "subClashURI": "",
  115. "subClashEnableRouting": "false",
  116. "subClashRules": "",
  117. "subJsonMux": "",
  118. "subJsonRules": "",
  119. "subJsonFinalMask": "",
  120. "subJsonObservatory": "",
  121. "subThemeDir": "",
  122. "datepicker": "gregorian",
  123. "warp": "",
  124. "warpUpdateInterval": "0",
  125. "nord": "",
  126. "pia": "",
  127. "externalTrafficInformEnable": "false",
  128. "externalTrafficInformURI": "",
  129. "restartXrayOnClientDisable": "true",
  130. "xrayOutboundTestUrl": "https://www.google.com/generate_204",
  131. "panelOutbound": "",
  132. "devChannelEnable": "false",
  133. // LDAP defaults
  134. "ldapEnable": "false",
  135. "ldapHost": "",
  136. "ldapPort": "389",
  137. "ldapUseTLS": "false",
  138. "ldapInsecureSkipVerify": "false",
  139. "ldapBindDN": "",
  140. "ldapPassword": "",
  141. "ldapBaseDN": "",
  142. "ldapUserFilter": "(objectClass=person)",
  143. "ldapUserAttr": "mail",
  144. "ldapVlessField": "vless_enabled",
  145. "ldapSyncCron": "@every 1m",
  146. "ldapFlagField": "",
  147. "ldapTruthyValues": "true,1,yes,on",
  148. "ldapInvertFlag": "false",
  149. "ldapInboundTags": "",
  150. "ldapAutoCreate": "false",
  151. "ldapAutoDelete": "false",
  152. "ldapDefaultTotalGB": "0",
  153. "ldapDefaultExpiryDays": "0",
  154. "ldapDefaultLimitIP": "0",
  155. // Event bus — per-subscriber event filtering (empty = all disabled)
  156. "tgEnabledEvents": "login.attempt,cpu.high",
  157. "smtpEnabledEvents": "login.attempt,cpu.high",
  158. "smtpCpu": "80",
  159. "smtpMemory": "80",
  160. // Consecutive failed observatory probes before an outbound.down event fires
  161. "outboundDownThreshold": "3",
  162. // Email (SMTP) notifications
  163. "smtpEnable": "false",
  164. "smtpHost": "",
  165. "smtpPort": "587",
  166. "smtpUsername": "",
  167. "smtpPassword": "",
  168. "smtpFrom": "",
  169. "smtpFromName": "",
  170. "smtpTo": "",
  171. "smtpEncryptionType": "starttls", // no, starttls, tls
  172. }
  173. // SettingService provides business logic for application settings management.
  174. // It handles configuration storage, retrieval, and validation for all system settings.
  175. type SettingService struct{}
  176. func (s *SettingService) GetDefaultJSONConfig() (any, error) {
  177. var jsonData any
  178. err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)
  179. if err != nil {
  180. return nil, err
  181. }
  182. return jsonData, nil
  183. }
  184. func (s *SettingService) GetAllSetting() (*entity.AllSetting, error) {
  185. db := database.GetDB()
  186. settings := make([]*model.Setting, 0)
  187. err := db.Model(model.Setting{}).Not("key = ?", "xrayTemplateConfig").Find(&settings).Error
  188. if err != nil {
  189. return nil, err
  190. }
  191. allSetting := &entity.AllSetting{}
  192. t := reflect.TypeFor[entity.AllSetting]()
  193. v := reflect.ValueOf(allSetting).Elem()
  194. fields := reflect_util.GetFields(t)
  195. setSetting := func(key, value string) (err error) {
  196. defer func() {
  197. panicErr := recover()
  198. if panicErr != nil {
  199. err = errors.New(fmt.Sprint(panicErr))
  200. }
  201. }()
  202. var found bool
  203. var field reflect.StructField
  204. for _, f := range fields {
  205. if f.Tag.Get("json") == key {
  206. field = f
  207. found = true
  208. break
  209. }
  210. }
  211. if !found {
  212. // Some settings are automatically generated, no need to return to the front end to modify the user
  213. return nil
  214. }
  215. fieldV := v.FieldByName(field.Name)
  216. switch t := fieldV.Interface().(type) {
  217. case int:
  218. n, err := strconv.ParseInt(effectiveSettingValue(key, value), 10, 64)
  219. if err != nil {
  220. return err
  221. }
  222. fieldV.SetInt(n)
  223. case string:
  224. fieldV.SetString(value)
  225. case bool:
  226. fieldV.SetBool(effectiveSettingValue(key, value) == "true")
  227. default:
  228. return common.NewErrorf("unknown field %v type %v", key, t)
  229. }
  230. return
  231. }
  232. keyMap := map[string]bool{}
  233. for _, setting := range settings {
  234. err := setSetting(setting.Key, setting.Value)
  235. if err != nil {
  236. return nil, err
  237. }
  238. keyMap[setting.Key] = true
  239. }
  240. for key, value := range defaultValueMap {
  241. if keyMap[key] {
  242. continue
  243. }
  244. err := setSetting(key, value)
  245. if err != nil {
  246. return nil, err
  247. }
  248. }
  249. return allSetting, nil
  250. }
  251. func (s *SettingService) GetAllSettingView() (*entity.AllSettingView, error) {
  252. allSetting, err := s.GetAllSetting()
  253. if err != nil {
  254. return nil, err
  255. }
  256. view := &entity.AllSettingView{AllSetting: *allSetting}
  257. view.HasTgBotToken = secretConfigured(allSetting.TgBotToken)
  258. view.HasTwoFactorToken = secretConfigured(allSetting.TwoFactorToken)
  259. view.HasLdapPassword = secretConfigured(allSetting.LdapPassword)
  260. view.HasWarpSecret = secretConfigured(mustString(s.GetWarp()))
  261. view.HasNordSecret = secretConfigured(mustString(s.GetNord()))
  262. view.HasSmtpPassword = secretConfigured(allSetting.SmtpPassword)
  263. var apiTokenCount int64
  264. if err := database.GetDB().Model(model.ApiToken{}).Where("enabled = ?", true).Count(&apiTokenCount).Error; err == nil {
  265. view.HasApiToken = apiTokenCount > 0
  266. }
  267. view.TgBotToken = ""
  268. view.TwoFactorToken = ""
  269. view.LdapPassword = ""
  270. view.SmtpPassword = ""
  271. return view, nil
  272. }
  273. func secretConfigured(value string) bool {
  274. return strings.TrimSpace(value) != ""
  275. }
  276. func mustString(value string, _ error) string {
  277. return value
  278. }
  279. func getEnv(key, fallback string) string {
  280. val, ok := os.LookupEnv(key)
  281. if !ok {
  282. return fallback
  283. }
  284. val = strings.TrimSpace(val)
  285. if val == "" {
  286. return fallback
  287. }
  288. return val
  289. }
  290. func (s *SettingService) ResetSettings() error {
  291. db := database.GetDB()
  292. return db.Transaction(func(tx *gorm.DB) error {
  293. if err := tx.Where("1 = 1").Delete(model.Setting{}).Error; err != nil {
  294. return err
  295. }
  296. paths := []model.Setting{
  297. {Key: "subPath", Value: "/" + random.NumLower(16) + "/"},
  298. {Key: "subJsonPath", Value: "/" + random.NumLower(16) + "/"},
  299. {Key: "subClashPath", Value: "/" + random.NumLower(16) + "/"},
  300. }
  301. return tx.Create(&paths).Error
  302. })
  303. }
  304. func (s *SettingService) getSetting(key string) (*model.Setting, error) {
  305. db := database.GetDB()
  306. setting := &model.Setting{}
  307. err := db.Model(model.Setting{}).Where("key = ?", key).First(setting).Error
  308. if err != nil {
  309. return nil, err
  310. }
  311. return setting, nil
  312. }
  313. func (s *SettingService) saveSetting(key string, value string) error {
  314. setting, err := s.getSetting(key)
  315. db := database.GetDB()
  316. if database.IsNotFound(err) {
  317. return db.Create(&model.Setting{
  318. Key: key,
  319. Value: value,
  320. }).Error
  321. } else if err != nil {
  322. return err
  323. }
  324. setting.Key = key
  325. setting.Value = value
  326. return db.Save(setting).Error
  327. }
  328. func (s *SettingService) getString(key string) (string, error) {
  329. setting, err := s.getSetting(key)
  330. if database.IsNotFound(err) {
  331. value, ok := defaultValueMap[key]
  332. if !ok {
  333. return "", common.NewErrorf("key <%v> not in defaultValueMap", key)
  334. }
  335. return value, nil
  336. } else if err != nil {
  337. return "", err
  338. }
  339. return setting.Value, nil
  340. }
  341. func (s *SettingService) setString(key string, value string) error {
  342. return s.saveSetting(key, value)
  343. }
  344. func effectiveSettingValue(key, stored string) string {
  345. if stored == "" {
  346. if def, ok := defaultValueMap[key]; ok {
  347. return def
  348. }
  349. }
  350. return stored
  351. }
  352. func (s *SettingService) getBool(key string) (bool, error) {
  353. str, err := s.getString(key)
  354. if err != nil {
  355. return false, err
  356. }
  357. return strconv.ParseBool(effectiveSettingValue(key, str))
  358. }
  359. func (s *SettingService) setBool(key string, value bool) error {
  360. return s.setString(key, strconv.FormatBool(value))
  361. }
  362. func (s *SettingService) getInt(key string) (int, error) {
  363. str, err := s.getString(key)
  364. if err != nil {
  365. return 0, err
  366. }
  367. return strconv.Atoi(effectiveSettingValue(key, str))
  368. }
  369. func (s *SettingService) setInt(key string, value int) error {
  370. return s.setString(key, strconv.Itoa(value))
  371. }
  372. func (s *SettingService) GetWarpLastUpdate() (int64, error) {
  373. setting, err := s.getSetting("warpLastUpdate")
  374. if database.IsNotFound(err) {
  375. return 0, nil
  376. }
  377. if err != nil {
  378. return 0, err
  379. }
  380. if setting.Value == "" {
  381. return 0, nil
  382. }
  383. return strconv.ParseInt(setting.Value, 10, 64)
  384. }
  385. func (s *SettingService) SetWarpLastUpdate(val int64) error {
  386. return s.saveSetting("warpLastUpdate", strconv.FormatInt(val, 10))
  387. }
  388. func (s *SettingService) SetWarpUpdateInterval(val int) error {
  389. return s.setInt("warpUpdateInterval", val)
  390. }
  391. func (s *SettingService) GetXrayConfigTemplate() (string, error) {
  392. return s.getString("xrayTemplateConfig")
  393. }
  394. func (s *SettingService) GetXrayOutboundTestUrl() (string, error) {
  395. return s.getString("xrayOutboundTestUrl")
  396. }
  397. func (s *SettingService) SetXrayOutboundTestUrl(url string) error {
  398. clean, err := SanitizeHTTPURL(url)
  399. if err != nil {
  400. return err
  401. }
  402. return s.setString("xrayOutboundTestUrl", clean)
  403. }
  404. func (s *SettingService) GetListen() (string, error) {
  405. return s.getString("webListen")
  406. }
  407. func (s *SettingService) SetListen(ip string) error {
  408. return s.setString("webListen", ip)
  409. }
  410. func (s *SettingService) GetWebDomain() (string, error) {
  411. return s.getString("webDomain")
  412. }
  413. func (s *SettingService) GetTgBotToken() (string, error) {
  414. return s.getString("tgBotToken")
  415. }
  416. func (s *SettingService) SetTgBotToken(token string) error {
  417. return s.setString("tgBotToken", token)
  418. }
  419. func (s *SettingService) GetTgBotProxy() (string, error) {
  420. return s.getString("tgBotProxy")
  421. }
  422. func (s *SettingService) SetTgBotProxy(token string) error {
  423. return s.setString("tgBotProxy", token)
  424. }
  425. // GetPanelOutbound returns the Xray outbound tag the panel's own outbound
  426. // requests (version checks, Telegram, subscription fetches) are routed through.
  427. func (s *SettingService) GetPanelOutbound() (string, error) {
  428. return s.getString("panelOutbound")
  429. }
  430. func (s *SettingService) SetPanelOutbound(tag string) error {
  431. return s.setString("panelOutbound", tag)
  432. }
  433. // PanelEgressProxyURL resolves the loopback SOCKS bridge that the generated
  434. // config exposes when a panel outbound is configured (see injectPanelEgress).
  435. // It returns "" — meaning a direct connection — when the feature is off or
  436. // the bridge is not present in the running core yet.
  437. func (s *SettingService) PanelEgressProxyURL() string {
  438. tag, err := s.GetPanelOutbound()
  439. if err != nil || tag == "" {
  440. return ""
  441. }
  442. proc := XrayProcess()
  443. if proc == nil || !proc.IsRunning() {
  444. logger.Warning("panel outbound [", tag, "] is set but Xray is not running, using a direct connection")
  445. return ""
  446. }
  447. cfg := proc.GetConfig()
  448. if cfg == nil {
  449. return ""
  450. }
  451. for i := range cfg.InboundConfigs {
  452. if cfg.InboundConfigs[i].Tag == PanelEgressInboundTag {
  453. return fmt.Sprintf("socks5://127.0.0.1:%d", cfg.InboundConfigs[i].Port)
  454. }
  455. }
  456. logger.Warning("panel outbound [", tag, "] is set but the egress bridge is not in the running config, using a direct connection")
  457. return ""
  458. }
  459. func (s *SettingService) NodeEgressProxyURL(nodeID int) string {
  460. tag := NodeEgressInboundTag(nodeID)
  461. proc := XrayProcess()
  462. if proc == nil || !proc.IsRunning() {
  463. logger.Warning("node outbound [", tag, "] is set but Xray is not running, using a direct connection")
  464. return ""
  465. }
  466. cfg := proc.GetConfig()
  467. if cfg == nil {
  468. return ""
  469. }
  470. for i := range cfg.InboundConfigs {
  471. if cfg.InboundConfigs[i].Tag == tag {
  472. return fmt.Sprintf("socks5://127.0.0.1:%d", cfg.InboundConfigs[i].Port)
  473. }
  474. }
  475. logger.Warning("node outbound [", tag, "] is set but the egress bridge is not in the running config, using a direct connection")
  476. return ""
  477. }
  478. // NewProxiedHTTPClient returns an HTTP client that routes the panel's own
  479. // outbound requests through the configured panel outbound (via the loopback
  480. // SOCKS bridge in the running Xray). When the feature is off or the bridge
  481. // is unavailable it falls back to a direct client.
  482. func (s *SettingService) NewProxiedHTTPClient(timeout time.Duration) *http.Client {
  483. proxyUrl := s.PanelEgressProxyURL()
  484. client, err := netproxy.NewHTTPClient(proxyUrl, timeout)
  485. if err != nil {
  486. logger.Warningf("Invalid panel egress proxy %q, using direct connection: %v", proxyUrl, err)
  487. return &http.Client{Timeout: timeout}
  488. }
  489. return client
  490. }
  491. func (s *SettingService) GetTgBotAPIServer() (string, error) {
  492. return s.getString("tgBotAPIServer")
  493. }
  494. func (s *SettingService) SetTgBotAPIServer(token string) error {
  495. return s.setString("tgBotAPIServer", token)
  496. }
  497. func (s *SettingService) GetTgBotChatId() (string, error) {
  498. return s.getString("tgBotChatId")
  499. }
  500. func (s *SettingService) SetTgBotChatId(chatIds string) error {
  501. return s.setString("tgBotChatId", chatIds)
  502. }
  503. func (s *SettingService) GetTgbotEnabled() (bool, error) {
  504. return s.getBool("tgBotEnable")
  505. }
  506. func (s *SettingService) SetTgbotEnabled(value bool) error {
  507. return s.setBool("tgBotEnable", value)
  508. }
  509. func (s *SettingService) GetTgbotRuntime() (string, error) {
  510. return s.getString("tgRunTime")
  511. }
  512. func (s *SettingService) SetTgbotRuntime(time string) error {
  513. return s.setString("tgRunTime", time)
  514. }
  515. func (s *SettingService) GetTgBotBackup() (bool, error) {
  516. return s.getBool("tgBotBackup")
  517. }
  518. func (s *SettingService) GetTgCpu() (int, error) {
  519. return s.getInt("tgCpu")
  520. }
  521. func (s *SettingService) GetTgMemory() (int, error) {
  522. return s.getInt("tgMemory")
  523. }
  524. func (s *SettingService) SetTgMemory(value int) error {
  525. return s.setInt("tgMemory", value)
  526. }
  527. func (s *SettingService) GetTgLang() (string, error) {
  528. return s.getString("tgLang")
  529. }
  530. func (s *SettingService) GetTwoFactorEnable() (bool, error) {
  531. return s.getBool("twoFactorEnable")
  532. }
  533. func (s *SettingService) SetTwoFactorEnable(value bool) error {
  534. return s.setBool("twoFactorEnable", value)
  535. }
  536. func (s *SettingService) GetTwoFactorToken() (string, error) {
  537. return s.getString("twoFactorToken")
  538. }
  539. func (s *SettingService) SetTwoFactorToken(value string) error {
  540. return s.setString("twoFactorToken", value)
  541. }
  542. func (s *SettingService) VerifyTwoFactorCode(code string) error {
  543. enabled, err := s.GetTwoFactorEnable()
  544. if err != nil {
  545. return err
  546. }
  547. if !enabled {
  548. return nil
  549. }
  550. token, err := s.GetTwoFactorToken()
  551. if err != nil {
  552. return err
  553. }
  554. if strings.TrimSpace(token) == "" || !gotp.NewDefaultTOTP(token).Verify(strings.TrimSpace(code), time.Now().Unix()) {
  555. return common.NewError("invalid two factor code")
  556. }
  557. return nil
  558. }
  559. func (s *SettingService) GetPort() (int, error) {
  560. return s.getInt("webPort")
  561. }
  562. func (s *SettingService) SetPort(port int) error {
  563. return s.setInt("webPort", port)
  564. }
  565. func (s *SettingService) SetCertFile(webCertFile string) error {
  566. return s.setString("webCertFile", webCertFile)
  567. }
  568. func (s *SettingService) GetCertFile() (string, error) {
  569. return s.getString("webCertFile")
  570. }
  571. func (s *SettingService) SetKeyFile(webKeyFile string) error {
  572. return s.setString("webKeyFile", webKeyFile)
  573. }
  574. func (s *SettingService) GetKeyFile() (string, error) {
  575. return s.getString("webKeyFile")
  576. }
  577. func (s *SettingService) GetExpireDiff() (int, error) {
  578. return s.getInt("expireDiff")
  579. }
  580. func (s *SettingService) GetTrafficDiff() (int, error) {
  581. return s.getInt("trafficDiff")
  582. }
  583. func (s *SettingService) GetSessionMaxAge() (int, error) {
  584. return s.getInt("sessionMaxAge")
  585. }
  586. // GetIpLimitAllowlist returns the operator's trusted addresses and networks,
  587. // which the IP limit neither counts nor bans.
  588. func (s *SettingService) GetIpLimitAllowlist() (string, error) {
  589. return s.getString("ipLimitAllowlist")
  590. }
  591. func (s *SettingService) GetTrustedProxyCIDRs() (string, error) {
  592. return s.getString("trustedProxyCIDRs")
  593. }
  594. func (s *SettingService) GetRemarkTemplate() (string, error) {
  595. return s.getString("remarkTemplate")
  596. }
  597. func (s *SettingService) GetSubShowIdentityOnAllLinks() (bool, error) {
  598. return s.getBool("subShowIdentityOnAllLinks")
  599. }
  600. func (s *SettingService) GetSubInfoNodeEnable() (bool, error) {
  601. return s.getBool("subInfoNodeEnable")
  602. }
  603. func (s *SettingService) GetSubExpiredTemplate() (string, error) {
  604. return s.getString("subExpiredTemplate")
  605. }
  606. func (s *SettingService) GetSubTrafficDepletedTemplate() (string, error) {
  607. return s.getString("subTrafficDepletedTemplate")
  608. }
  609. func (s *SettingService) GetSecret() ([]byte, error) {
  610. secret, err := s.getString("secret")
  611. if secret == "" || secret == defaultValueMap["secret"] {
  612. if secret == "" {
  613. secret = defaultValueMap["secret"]
  614. }
  615. saveErr := s.saveSetting("secret", secret)
  616. if saveErr != nil {
  617. logger.Warning("save secret failed:", saveErr)
  618. }
  619. }
  620. return []byte(secret), err
  621. }
  622. // GetPanelGuid returns this panel's stable self-identifier, persisting a
  623. // freshly generated UUID on first read. It is the globally stable node
  624. // identity used to attribute online clients and inbounds to the physical
  625. // node that hosts them across a chain of nodes (#4983), where per-panel
  626. // autoincrement node ids are meaningless one hop away.
  627. func (s *SettingService) GetPanelGuid() (string, error) {
  628. guid, err := s.getString("panelGuid")
  629. if err != nil {
  630. return "", err
  631. }
  632. if guid == defaultValueMap["panelGuid"] {
  633. if saveErr := s.saveSetting("panelGuid", guid); saveErr != nil {
  634. logger.Warning("save panelGuid failed:", saveErr)
  635. }
  636. }
  637. return guid, nil
  638. }
  639. func (s *SettingService) SetBasePath(basePath string) error {
  640. if !strings.HasPrefix(basePath, "/") {
  641. basePath = "/" + basePath
  642. }
  643. if !strings.HasSuffix(basePath, "/") {
  644. basePath += "/"
  645. }
  646. return s.setString("webBasePath", basePath)
  647. }
  648. func (s *SettingService) GetBasePath() (string, error) {
  649. basePath, err := s.getString("webBasePath")
  650. if err != nil {
  651. return "", err
  652. }
  653. return normalizeBasePath(basePath), nil
  654. }
  655. func (s *SettingService) GetTimeLocation() (*time.Location, error) {
  656. l, err := s.getString("timeLocation")
  657. if err != nil {
  658. return nil, err
  659. }
  660. location, err := time.LoadLocation(l)
  661. if err != nil {
  662. defaultLocation := defaultValueMap["timeLocation"]
  663. logger.Errorf("location <%v> not exist, using default location: %v", l, defaultLocation)
  664. location, err = time.LoadLocation(defaultLocation)
  665. if err != nil {
  666. logger.Errorf("failed to load default location, using UTC: %v", err)
  667. return time.UTC, nil
  668. }
  669. return location, nil
  670. }
  671. return location, nil
  672. }
  673. func (s *SettingService) GetSubEnable() (bool, error) {
  674. return s.getBool("subEnable")
  675. }
  676. func (s *SettingService) GetSubJsonEnable() (bool, error) {
  677. return s.getBool("subJsonEnable")
  678. }
  679. func (s *SettingService) GetSubJsonAutoDetect() (bool, error) {
  680. return s.getBool("subJsonAutoDetect")
  681. }
  682. func (s *SettingService) GetSubJsonAlwaysArray() (bool, error) {
  683. return s.getBool("subJsonAlwaysArray")
  684. }
  685. func (s *SettingService) GetSubJsonUserAgentRegex() (string, error) {
  686. return s.getString("subJsonUserAgentRegex")
  687. }
  688. func (s *SettingService) GetSubClashAutoDetect() (bool, error) {
  689. return s.getBool("subClashAutoDetect")
  690. }
  691. func (s *SettingService) GetSubClashUserAgentRegex() (string, error) {
  692. return s.getString("subClashUserAgentRegex")
  693. }
  694. func (s *SettingService) GetSubTitle() (string, error) {
  695. return s.getString("subTitle")
  696. }
  697. func (s *SettingService) GetSubSupportUrl() (string, error) {
  698. value, err := s.getString("subSupportUrl")
  699. return common.EnsureURLScheme(value), err
  700. }
  701. func (s *SettingService) GetSubProfileUrl() (string, error) {
  702. value, err := s.getString("subProfileUrl")
  703. return common.EnsureURLScheme(value), err
  704. }
  705. func (s *SettingService) GetSubAnnounce() (string, error) {
  706. return s.getString("subAnnounce")
  707. }
  708. func (s *SettingService) GetSubEnableRouting() (bool, error) {
  709. return s.getBool("subEnableRouting")
  710. }
  711. func (s *SettingService) GetSubRoutingRules() (string, error) {
  712. return s.getString("subRoutingRules")
  713. }
  714. func (s *SettingService) GetSubHideSettings() (bool, error) {
  715. return s.getBool("subHideSettings")
  716. }
  717. func (s *SettingService) GetSubIncyEnableRouting() (bool, error) {
  718. return s.getBool("subIncyEnableRouting")
  719. }
  720. func (s *SettingService) GetSubIncyRoutingRules() (string, error) {
  721. return s.getString("subIncyRoutingRules")
  722. }
  723. func (s *SettingService) GetSubListen() (string, error) {
  724. return s.getString("subListen")
  725. }
  726. func (s *SettingService) GetSubPort() (int, error) {
  727. return s.getInt("subPort")
  728. }
  729. func (s *SettingService) GetSubPath() (string, error) {
  730. return s.getString("subPath")
  731. }
  732. func (s *SettingService) GetSubJsonPath() (string, error) {
  733. return s.getString("subJsonPath")
  734. }
  735. func (s *SettingService) GetSubDomain() (string, error) {
  736. return s.getString("subDomain")
  737. }
  738. func (s *SettingService) SetSubCertFile(subCertFile string) error {
  739. return s.setString("subCertFile", subCertFile)
  740. }
  741. func (s *SettingService) GetSubCertFile() (string, error) {
  742. return s.getString("subCertFile")
  743. }
  744. func (s *SettingService) SetSubKeyFile(subKeyFile string) error {
  745. return s.setString("subKeyFile", subKeyFile)
  746. }
  747. func (s *SettingService) GetSubKeyFile() (string, error) {
  748. return s.getString("subKeyFile")
  749. }
  750. func (s *SettingService) GetSubUpdates() (string, error) {
  751. return s.getString("subUpdates")
  752. }
  753. func (s *SettingService) GetSubEncrypt() (bool, error) {
  754. return s.getBool("subEncrypt")
  755. }
  756. func (s *SettingService) GetPageSize() (int, error) {
  757. return s.getInt("pageSize")
  758. }
  759. func (s *SettingService) GetSubURI() (string, error) {
  760. return s.getString("subURI")
  761. }
  762. func (s *SettingService) GetSubJsonURI() (string, error) {
  763. return s.getString("subJsonURI")
  764. }
  765. func (s *SettingService) GetSubClashEnable() (bool, error) {
  766. return s.getBool("subClashEnable")
  767. }
  768. func (s *SettingService) GetSubClashPath() (string, error) {
  769. return s.getString("subClashPath")
  770. }
  771. func (s *SettingService) GetSubClashURI() (string, error) {
  772. return s.getString("subClashURI")
  773. }
  774. func (s *SettingService) GetSubClashEnableRouting() (bool, error) {
  775. return s.getBool("subClashEnableRouting")
  776. }
  777. func (s *SettingService) GetSubClashRules() (string, error) {
  778. return s.getString("subClashRules")
  779. }
  780. func (s *SettingService) GetSubJsonMux() (string, error) {
  781. return s.getString("subJsonMux")
  782. }
  783. func (s *SettingService) GetSubJsonRules() (string, error) {
  784. return s.getString("subJsonRules")
  785. }
  786. func (s *SettingService) GetSubJsonFinalMask() (string, error) {
  787. return s.getString("subJsonFinalMask")
  788. }
  789. func (s *SettingService) GetSubJsonObservatory() (string, error) {
  790. return s.getString("subJsonObservatory")
  791. }
  792. func (s *SettingService) GetSubThemeDir() (string, error) {
  793. return s.getString("subThemeDir")
  794. }
  795. func (s *SettingService) GetDatepicker() (string, error) {
  796. return s.getString("datepicker")
  797. }
  798. func (s *SettingService) GetWarp() (string, error) {
  799. return s.getString("warp")
  800. }
  801. func (s *SettingService) SetWarp(data string) error {
  802. return s.setString("warp", data)
  803. }
  804. func (s *SettingService) GetNord() (string, error) {
  805. return s.getString("nord")
  806. }
  807. func (s *SettingService) SetNord(data string) error {
  808. return s.setString("nord", data)
  809. }
  810. func (s *SettingService) GetPia() (string, error) {
  811. return s.getString("pia")
  812. }
  813. func (s *SettingService) SetPia(data string) error {
  814. return s.setString("pia", data)
  815. }
  816. func (s *SettingService) GetExternalTrafficInformEnable() (bool, error) {
  817. return s.getBool("externalTrafficInformEnable")
  818. }
  819. func (s *SettingService) SetExternalTrafficInformEnable(value bool) error {
  820. return s.setBool("externalTrafficInformEnable", value)
  821. }
  822. func (s *SettingService) GetExternalTrafficInformURI() (string, error) {
  823. return s.getString("externalTrafficInformURI")
  824. }
  825. func (s *SettingService) SetExternalTrafficInformURI(InformURI string) error {
  826. return s.setString("externalTrafficInformURI", InformURI)
  827. }
  828. func (s *SettingService) GetRestartXrayOnClientDisable() (bool, error) {
  829. return s.getBool("restartXrayOnClientDisable")
  830. }
  831. func (s *SettingService) SetRestartXrayOnClientDisable(value bool) error {
  832. return s.setBool("restartXrayOnClientDisable", value)
  833. }
  834. // GetDevChannelEnable reports whether the panel self-update tracks the rolling
  835. // per-commit dev release instead of the latest stable tag.
  836. func (s *SettingService) GetDevChannelEnable() (bool, error) {
  837. return s.getBool("devChannelEnable")
  838. }
  839. func (s *SettingService) SetDevChannelEnable(value bool) error {
  840. return s.setBool("devChannelEnable", value)
  841. }
  842. // GetIpLimitEnable reports whether the IP-limit feature is available. Always
  843. // true since the panel enforces limits via the core's online-stats API; on an
  844. // older core the job falls back to access-log parsing and warns there when the
  845. // log is missing, so the UI no longer hides the field behind that condition.
  846. func (s *SettingService) GetIpLimitEnable() (bool, error) {
  847. return true, nil
  848. }
  849. // GetAccessLogEnable reports whether an Xray access log is configured. Used by
  850. // the UI for features that genuinely read the log file (the xray log viewer) —
  851. // distinct from IP limiting, which works without it.
  852. func (s *SettingService) GetAccessLogEnable() (bool, error) {
  853. accessLogPath, err := xray.GetAccessLogPath()
  854. if err != nil {
  855. return false, err
  856. }
  857. return (accessLogPath != "none" && accessLogPath != ""), nil
  858. }
  859. // GetLdapEnable returns whether LDAP is enabled.
  860. func (s *SettingService) GetLdapEnable() (bool, error) {
  861. return s.getBool("ldapEnable")
  862. }
  863. func (s *SettingService) GetLdapHost() (string, error) {
  864. return s.getString("ldapHost")
  865. }
  866. func (s *SettingService) GetLdapPort() (int, error) {
  867. return s.getInt("ldapPort")
  868. }
  869. func (s *SettingService) GetLdapUseTLS() (bool, error) {
  870. return s.getBool("ldapUseTLS")
  871. }
  872. func (s *SettingService) GetLdapInsecureSkipVerify() (bool, error) {
  873. return s.getBool("ldapInsecureSkipVerify")
  874. }
  875. func (s *SettingService) GetLdapBindDN() (string, error) {
  876. return s.getString("ldapBindDN")
  877. }
  878. func (s *SettingService) GetLdapPassword() (string, error) {
  879. return s.getString("ldapPassword")
  880. }
  881. func (s *SettingService) GetLdapBaseDN() (string, error) {
  882. return s.getString("ldapBaseDN")
  883. }
  884. func (s *SettingService) GetLdapUserFilter() (string, error) {
  885. return s.getString("ldapUserFilter")
  886. }
  887. func (s *SettingService) GetLdapUserAttr() (string, error) {
  888. return s.getString("ldapUserAttr")
  889. }
  890. func (s *SettingService) GetLdapVlessField() (string, error) {
  891. return s.getString("ldapVlessField")
  892. }
  893. func (s *SettingService) GetLdapSyncCron() (string, error) {
  894. return s.getString("ldapSyncCron")
  895. }
  896. func (s *SettingService) GetLdapFlagField() (string, error) {
  897. return s.getString("ldapFlagField")
  898. }
  899. func (s *SettingService) GetLdapTruthyValues() (string, error) {
  900. return s.getString("ldapTruthyValues")
  901. }
  902. func (s *SettingService) GetLdapInvertFlag() (bool, error) {
  903. return s.getBool("ldapInvertFlag")
  904. }
  905. func (s *SettingService) GetLdapInboundTags() (string, error) {
  906. return s.getString("ldapInboundTags")
  907. }
  908. func (s *SettingService) GetLdapAutoCreate() (bool, error) {
  909. return s.getBool("ldapAutoCreate")
  910. }
  911. func (s *SettingService) GetLdapAutoDelete() (bool, error) {
  912. return s.getBool("ldapAutoDelete")
  913. }
  914. func (s *SettingService) GetLdapDefaultTotalGB() (int, error) {
  915. return s.getInt("ldapDefaultTotalGB")
  916. }
  917. func (s *SettingService) GetLdapDefaultExpiryDays() (int, error) {
  918. return s.getInt("ldapDefaultExpiryDays")
  919. }
  920. func (s *SettingService) GetLdapDefaultLimitIP() (int, error) {
  921. return s.getInt("ldapDefaultLimitIP")
  922. }
  923. // Event bus — per-subscriber event filtering
  924. func (s *SettingService) GetTgEnabledEvents() (string, error) {
  925. return s.getString("tgEnabledEvents")
  926. }
  927. func (s *SettingService) SetTgEnabledEvents(events string) error {
  928. return s.setString("tgEnabledEvents", events)
  929. }
  930. func (s *SettingService) GetSmtpEnabledEvents() (string, error) {
  931. return s.getString("smtpEnabledEvents")
  932. }
  933. func (s *SettingService) SetSmtpEnabledEvents(events string) error {
  934. return s.setString("smtpEnabledEvents", events)
  935. }
  936. // Email (SMTP) settings
  937. func (s *SettingService) GetSmtpEnable() (bool, error) {
  938. return s.getBool("smtpEnable")
  939. }
  940. func (s *SettingService) SetSmtpEnable(value bool) error {
  941. return s.setBool("smtpEnable", value)
  942. }
  943. func (s *SettingService) GetSmtpHost() (string, error) {
  944. return s.getString("smtpHost")
  945. }
  946. func (s *SettingService) SetSmtpHost(value string) error {
  947. return s.setString("smtpHost", value)
  948. }
  949. func (s *SettingService) GetSmtpPort() (int, error) {
  950. return s.getInt("smtpPort")
  951. }
  952. func (s *SettingService) SetSmtpPort(value int) error {
  953. return s.setInt("smtpPort", value)
  954. }
  955. func (s *SettingService) GetSmtpUsername() (string, error) {
  956. return s.getString("smtpUsername")
  957. }
  958. func (s *SettingService) SetSmtpUsername(value string) error {
  959. return s.setString("smtpUsername", value)
  960. }
  961. func (s *SettingService) GetSmtpFrom() (string, error) {
  962. return s.getString("smtpFrom")
  963. }
  964. func (s *SettingService) SetSmtpFrom(value string) error {
  965. return s.setString("smtpFrom", value)
  966. }
  967. func (s *SettingService) GetSmtpFromName() (string, error) {
  968. return s.getString("smtpFromName")
  969. }
  970. func (s *SettingService) SetSmtpFromName(value string) error {
  971. return s.setString("smtpFromName", value)
  972. }
  973. func (s *SettingService) GetSmtpPassword() (string, error) {
  974. return s.getString("smtpPassword")
  975. }
  976. func (s *SettingService) SetSmtpPassword(value string) error {
  977. return s.setString("smtpPassword", value)
  978. }
  979. func (s *SettingService) GetSmtpTo() (string, error) {
  980. return s.getString("smtpTo")
  981. }
  982. func (s *SettingService) SetSmtpTo(value string) error {
  983. return s.setString("smtpTo", value)
  984. }
  985. func (s *SettingService) GetSmtpEncryptionType() (string, error) {
  986. return s.getString("smtpEncryptionType")
  987. }
  988. func (s *SettingService) SetSmtpEncryptionType(value string) error {
  989. return s.setString("smtpEncryptionType", value)
  990. }
  991. func (s *SettingService) GetSmtpCpu() (int, error) {
  992. return s.getInt("smtpCpu")
  993. }
  994. func (s *SettingService) SetSmtpCpu(value int) error {
  995. return s.setInt("smtpCpu", value)
  996. }
  997. func (s *SettingService) GetSmtpMemory() (int, error) {
  998. return s.getInt("smtpMemory")
  999. }
  1000. func (s *SettingService) SetSmtpMemory(value int) error {
  1001. return s.setInt("smtpMemory", value)
  1002. }
  1003. // GetOutboundDownThreshold returns how many consecutive failed observatory
  1004. // probes an outbound must accumulate before an outbound.down notification is
  1005. // emitted. 1 preserves the legacy "notify on the first failed probe" behaviour.
  1006. func (s *SettingService) GetOutboundDownThreshold() (int, error) {
  1007. return s.getInt("outboundDownThreshold")
  1008. }
  1009. func (s *SettingService) SetOutboundDownThreshold(value int) error {
  1010. return s.setInt("outboundDownThreshold", value)
  1011. }
  1012. // SecretClears marks redacted secrets the user explicitly emptied. Without a
  1013. // flag, a blank submitted secret means "unchanged" (the field is always served
  1014. // blank to the browser) and the stored value is preserved.
  1015. type SecretClears struct {
  1016. TgBotToken bool
  1017. LdapPassword bool
  1018. SmtpPassword bool
  1019. }
  1020. func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears SecretClears) error {
  1021. if err := s.preserveRedactedSecrets(allSetting, clears); err != nil {
  1022. return err
  1023. }
  1024. if err := validateSettingsURLs(allSetting); err != nil {
  1025. return err
  1026. }
  1027. if err := validateSubUserAgentRegexes(allSetting); err != nil {
  1028. return err
  1029. }
  1030. if err := allSetting.CheckValid(); err != nil {
  1031. return err
  1032. }
  1033. v := reflect.ValueOf(allSetting).Elem()
  1034. t := reflect.TypeFor[entity.AllSetting]()
  1035. fields := reflect_util.GetFields(t)
  1036. db := database.GetDB()
  1037. return db.Transaction(func(tx *gorm.DB) error {
  1038. var existing []*model.Setting
  1039. if err := tx.Find(&existing).Error; err != nil {
  1040. return err
  1041. }
  1042. byKey := make(map[string]*model.Setting, len(existing))
  1043. for _, st := range existing {
  1044. byKey[st.Key] = st
  1045. }
  1046. for _, field := range fields {
  1047. key := field.Tag.Get("json")
  1048. fieldV := v.FieldByName(field.Name)
  1049. value := fmt.Sprint(fieldV.Interface())
  1050. if st, ok := byKey[key]; ok {
  1051. if st.Value == value {
  1052. continue
  1053. }
  1054. st.Value = value
  1055. if err := tx.Save(st).Error; err != nil {
  1056. return err
  1057. }
  1058. continue
  1059. }
  1060. if err := tx.Create(&model.Setting{Key: key, Value: value}).Error; err != nil {
  1061. return err
  1062. }
  1063. }
  1064. return nil
  1065. })
  1066. }
  1067. func validateSubUserAgentRegexes(allSetting *entity.AllSetting) error {
  1068. jsonPattern, err := validateSubUserAgentRegex("Xray JSON", allSetting.SubJsonUserAgentRegex, DefaultSubJsonUserAgentRegex)
  1069. if err != nil {
  1070. return err
  1071. }
  1072. clashPattern, err := validateSubUserAgentRegex("Clash/Mihomo", allSetting.SubClashUserAgentRegex, DefaultSubClashUserAgentRegex)
  1073. if err != nil {
  1074. return err
  1075. }
  1076. allSetting.SubJsonUserAgentRegex = jsonPattern
  1077. allSetting.SubClashUserAgentRegex = clashPattern
  1078. return nil
  1079. }
  1080. func validateSubUserAgentRegex(name, pattern, defaultPattern string) (string, error) {
  1081. pattern = strings.TrimSpace(pattern)
  1082. effectivePattern := pattern
  1083. if effectivePattern == "" {
  1084. effectivePattern = defaultPattern
  1085. }
  1086. if len(effectivePattern) > maxRegexLength {
  1087. return "", common.NewErrorf("%s User-Agent regex must not exceed %d characters", name, maxRegexLength)
  1088. }
  1089. if _, err := regexp.Compile(effectivePattern); err != nil {
  1090. return "", common.NewErrorf("%s User-Agent regex is invalid: %v", name, err)
  1091. }
  1092. // Return the original pattern (empty string if cleared) so the caller
  1093. // can distinguish "user explicitly set empty" from "user set a value".
  1094. // The empty value is stored in the DB and inherited as runtime default.
  1095. return pattern, nil
  1096. }
  1097. func ValidateRegex(pattern string) error {
  1098. if len(pattern) > maxRegexLength {
  1099. return common.NewErrorf("Regular expression must not exceed %d characters", maxRegexLength)
  1100. }
  1101. if _, err := regexp.Compile(pattern); err != nil {
  1102. return common.NewError("Regular expression is invalid:", err)
  1103. }
  1104. return nil
  1105. }
  1106. func (s *SettingService) preserveRedactedSecrets(allSetting *entity.AllSetting, clears SecretClears) error {
  1107. if !clears.TgBotToken && strings.TrimSpace(allSetting.TgBotToken) == "" {
  1108. value, err := s.GetTgBotToken()
  1109. if err != nil {
  1110. return err
  1111. }
  1112. allSetting.TgBotToken = value
  1113. }
  1114. if !clears.LdapPassword && strings.TrimSpace(allSetting.LdapPassword) == "" {
  1115. value, err := s.GetLdapPassword()
  1116. if err != nil {
  1117. return err
  1118. }
  1119. allSetting.LdapPassword = value
  1120. }
  1121. if allSetting.TwoFactorEnable && strings.TrimSpace(allSetting.TwoFactorToken) == "" {
  1122. value, err := s.GetTwoFactorToken()
  1123. if err != nil {
  1124. return err
  1125. }
  1126. allSetting.TwoFactorToken = value
  1127. }
  1128. if !clears.SmtpPassword && strings.TrimSpace(allSetting.SmtpPassword) == "" {
  1129. value, err := s.GetSmtpPassword()
  1130. if err != nil {
  1131. return err
  1132. }
  1133. allSetting.SmtpPassword = value
  1134. }
  1135. return nil
  1136. }
  1137. func validateSettingsURLs(allSetting *entity.AllSetting) error {
  1138. if allSetting.ExternalTrafficInformURI != "" {
  1139. u, err := SanitizeHTTPURL(allSetting.ExternalTrafficInformURI)
  1140. if err != nil {
  1141. return common.NewError("external traffic inform URI is invalid:", err)
  1142. }
  1143. allSetting.ExternalTrafficInformURI = u
  1144. }
  1145. if allSetting.TgBotAPIServer != "" {
  1146. u, err := SanitizeHTTPURL(allSetting.TgBotAPIServer)
  1147. if err != nil {
  1148. return common.NewError("telegram API server URL is invalid:", err)
  1149. }
  1150. allSetting.TgBotAPIServer = u
  1151. }
  1152. // Support/profile links land in subscription headers and page data, where
  1153. // client apps resolve a scheme-less value against the panel's own domain.
  1154. // Non-http schemes (tg://, mailto:) are legitimate here, so only default
  1155. // the scheme instead of forcing SanitizeHTTPURL's http(s)-only rule.
  1156. allSetting.SubSupportUrl = common.EnsureURLScheme(allSetting.SubSupportUrl)
  1157. allSetting.SubProfileUrl = common.EnsureURLScheme(allSetting.SubProfileUrl)
  1158. for name, value := range map[string]*string{
  1159. "Happ routing source": &allSetting.SubRoutingRules,
  1160. "Clash/Mihomo routing source": &allSetting.SubClashRules,
  1161. "Incy routing source": &allSetting.SubIncyRoutingRules,
  1162. } {
  1163. if err := validateRemoteRoutingURLSetting(name, value); err != nil {
  1164. return err
  1165. }
  1166. }
  1167. return nil
  1168. }
  1169. func validateRemoteRoutingURLSetting(name string, value *string) error {
  1170. canonical, remote, err := common.ParseRemoteRoutingURL(*value)
  1171. if err != nil {
  1172. return common.NewError(name, err.Error())
  1173. }
  1174. if remote {
  1175. *value = canonical
  1176. }
  1177. return nil
  1178. }
  1179. func (s *SettingService) UpdateSecret(key string, value string) error {
  1180. switch key {
  1181. case "tgBotToken", "ldapPassword", "twoFactorToken":
  1182. return s.saveSetting(key, strings.TrimSpace(value))
  1183. default:
  1184. return common.NewError("secret key is not replaceable:", key)
  1185. }
  1186. }
  1187. func (s *SettingService) GetDefaultXrayConfig() (any, error) {
  1188. var jsonData any
  1189. err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)
  1190. if err != nil {
  1191. return nil, err
  1192. }
  1193. return jsonData, nil
  1194. }
  1195. func extractHostname(host string) string {
  1196. h, _, err := net.SplitHostPort(host)
  1197. // Err is not nil means host does not contain port
  1198. if err != nil {
  1199. h = host
  1200. }
  1201. ip := net.ParseIP(h)
  1202. // If it's not an IP, return as is
  1203. if ip == nil {
  1204. return h
  1205. }
  1206. // If it's an IPv4, return as is
  1207. if ip.To4() != nil {
  1208. return h
  1209. }
  1210. // IPv6 needs bracketing
  1211. return "[" + h + "]"
  1212. }
  1213. // BuildSubURIBase is shared by GetDefaultSettings (the panel's Client
  1214. // Information page) and the subscription page so both render subscription
  1215. // URLs identically.
  1216. func (s *SettingService) BuildSubURIBase(host string) string {
  1217. subPort, _ := s.GetSubPort()
  1218. subDomain, _ := s.GetSubDomain()
  1219. subKeyFile, _ := s.GetSubKeyFile()
  1220. subCertFile, _ := s.GetSubCertFile()
  1221. subTLS := subKeyFile != "" && subCertFile != ""
  1222. if subDomain == "" {
  1223. subDomain = extractHostname(host)
  1224. }
  1225. scheme := "http"
  1226. if subTLS {
  1227. scheme = "https"
  1228. }
  1229. if (subPort == 443 && subTLS) || (subPort == 80 && !subTLS) {
  1230. return scheme + "://" + subDomain
  1231. }
  1232. return fmt.Sprintf("%s://%s:%d", scheme, subDomain, subPort)
  1233. }
  1234. func (s *SettingService) GetDefaultSettings(host string) (any, error) {
  1235. type settingFunc func() (any, error)
  1236. settings := map[string]settingFunc{
  1237. "expireDiff": func() (any, error) { return s.GetExpireDiff() },
  1238. "trafficDiff": func() (any, error) { return s.GetTrafficDiff() },
  1239. "pageSize": func() (any, error) { return s.GetPageSize() },
  1240. "defaultCert": func() (any, error) { return s.GetCertFile() },
  1241. "defaultKey": func() (any, error) { return s.GetKeyFile() },
  1242. "tgBotEnable": func() (any, error) { return s.GetTgbotEnabled() },
  1243. "subThemeDir": func() (any, error) { return s.GetSubThemeDir() },
  1244. "subEnable": func() (any, error) { return s.GetSubEnable() },
  1245. "subJsonEnable": func() (any, error) { return s.GetSubJsonEnable() },
  1246. "subClashEnable": func() (any, error) { return s.GetSubClashEnable() },
  1247. "subTitle": func() (any, error) { return s.GetSubTitle() },
  1248. "subURI": func() (any, error) { return s.GetSubURI() },
  1249. "subJsonURI": func() (any, error) { return s.GetSubJsonURI() },
  1250. "subClashURI": func() (any, error) { return s.GetSubClashURI() },
  1251. "datepicker": func() (any, error) { return s.GetDatepicker() },
  1252. "ipLimitEnable": func() (any, error) { return s.GetIpLimitEnable() },
  1253. "accessLogEnable": func() (any, error) { return s.GetAccessLogEnable() },
  1254. "webDomain": func() (any, error) { return s.GetWebDomain() },
  1255. "subDomain": func() (any, error) { return s.GetSubDomain() },
  1256. "devChannelEnable": func() (any, error) { return s.GetDevChannelEnable() },
  1257. "isDevBuild": func() (any, error) { return config.IsDevBuild(), nil },
  1258. }
  1259. result := make(map[string]any)
  1260. for key, fn := range settings {
  1261. value, err := fn()
  1262. if err != nil {
  1263. return "", err
  1264. }
  1265. result[key] = value
  1266. }
  1267. subEnable := result["subEnable"].(bool)
  1268. subJsonEnable := false
  1269. if v, ok := result["subJsonEnable"]; ok {
  1270. if b, ok2 := v.(bool); ok2 {
  1271. subJsonEnable = b
  1272. }
  1273. }
  1274. subClashEnable := false
  1275. if v, ok := result["subClashEnable"]; ok {
  1276. if b, ok2 := v.(bool); ok2 {
  1277. subClashEnable = b
  1278. }
  1279. }
  1280. if (subEnable && result["subURI"].(string) == "") || (subJsonEnable && result["subJsonURI"].(string) == "") || (subClashEnable && result["subClashURI"].(string) == "") {
  1281. subURI := s.BuildSubURIBase(host)
  1282. subTitle, _ := s.GetSubTitle()
  1283. subPath, _ := s.GetSubPath()
  1284. subJsonPath, _ := s.GetSubJsonPath()
  1285. subClashPath, _ := s.GetSubClashPath()
  1286. if subEnable && result["subURI"].(string) == "" {
  1287. result["subURI"] = subURI + subPath
  1288. }
  1289. if result["subTitle"].(string) == "" {
  1290. result["subTitle"] = subTitle
  1291. }
  1292. if subJsonEnable && result["subJsonURI"].(string) == "" {
  1293. result["subJsonURI"] = subURI + subJsonPath
  1294. }
  1295. if subClashEnable && result["subClashURI"].(string) == "" {
  1296. result["subClashURI"] = subURI + subClashPath
  1297. }
  1298. }
  1299. return result, nil
  1300. }
  1301. var factoryDefaultSecretKeys = map[string]bool{
  1302. "tgBotToken": true,
  1303. "twoFactorToken": true,
  1304. "ldapPassword": true,
  1305. "smtpPassword": true,
  1306. }
  1307. /*
  1308. GetFactoryDefaults returns the shipped default value per setting, keyed by
  1309. the AllSetting json field name. Unlike GetDefaultSettings (which reports
  1310. current effective values), this is defaultValueMap projected through the
  1311. AllSetting field set: only keys that exist as an AllSetting json tag are
  1312. returned, minus the credential fields in factoryDefaultSecretKeys. Keys
  1313. with no AllSetting field (secret, panelGuid, the node mTLS material,
  1314. xrayTemplateConfig) are excluded structurally rather than by deny-list.
  1315. */
  1316. func (s *SettingService) GetFactoryDefaults() map[string]string {
  1317. result := make(map[string]string)
  1318. for _, field := range reflect_util.GetFields(reflect.TypeFor[entity.AllSetting]()) {
  1319. key := field.Tag.Get("json")
  1320. if key == "" || factoryDefaultSecretKeys[key] {
  1321. continue
  1322. }
  1323. if value, ok := defaultValueMap[key]; ok {
  1324. result[key] = value
  1325. }
  1326. }
  1327. return result
  1328. }