setting.go 40 KB

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