setting.go 35 KB

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