1
0

setting.go 42 KB

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