setting.go 41 KB

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