1
0

setting.go 34 KB

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