1
0

setting.go 54 KB

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