setting.go 35 KB

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