setting.go 43 KB

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