setting.go 42 KB

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