setting.go 44 KB

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