setting.go 43 KB

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