model.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. // Package model defines the database models and data structures used by the 3x-ui panel.
  2. package model
  3. import (
  4. "bytes"
  5. "crypto/rand"
  6. "encoding/hex"
  7. "encoding/json"
  8. "fmt"
  9. "strings"
  10. "github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
  11. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  12. )
  13. // Protocol represents the protocol type for Xray inbounds.
  14. type Protocol string
  15. // Protocol constants for different Xray inbound protocols.
  16. // Hysteria v2 is not a distinct protocol — it is plain "hysteria"
  17. // with streamSettings.version = 2. The share-link URI scheme
  18. // "hysteria2://" is independent of this and is still emitted by the
  19. // link generator when the stream version is 2.
  20. const (
  21. VMESS Protocol = "vmess"
  22. VLESS Protocol = "vless"
  23. Tunnel Protocol = "tunnel"
  24. HTTP Protocol = "http"
  25. Trojan Protocol = "trojan"
  26. Shadowsocks Protocol = "shadowsocks"
  27. Mixed Protocol = "mixed"
  28. WireGuard Protocol = "wireguard"
  29. Hysteria Protocol = "hysteria"
  30. MTProto Protocol = "mtproto"
  31. )
  32. // User represents a user account in the 3x-ui panel.
  33. type User struct {
  34. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  35. Username string `json:"username"`
  36. Password string `json:"password"`
  37. LoginEpoch int64 `json:"-" gorm:"default:0"`
  38. }
  39. // Inbound represents an Xray inbound configuration with traffic statistics and settings.
  40. type Inbound struct {
  41. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement" example:"1"` // Unique identifier
  42. UserId int `json:"-"` // Associated user ID
  43. Up int64 `json:"up" form:"up"` // Upload traffic in bytes
  44. Down int64 `json:"down" form:"down"` // Download traffic in bytes
  45. Total int64 `json:"total" form:"total"` // Total traffic limit in bytes
  46. Remark string `json:"remark" form:"remark" example:"VLESS-443"` // Human-readable remark
  47. SubSortIndex int `json:"subSortIndex" form:"subSortIndex" gorm:"default:1" validate:"omitempty,gte=1" example:"1"` // 1-based sort order of this inbound's links in subscription output only (lower first; ties by id)
  48. Enable bool `json:"enable" form:"enable" gorm:"index:idx_enable_traffic_reset,priority:1" example:"true"` // Whether the inbound is enabled
  49. ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` // Expiration timestamp
  50. TrafficReset string `json:"trafficReset" form:"trafficReset" gorm:"default:never;index:idx_enable_traffic_reset,priority:2" validate:"omitempty,oneof=never hourly daily weekly monthly"` // Traffic reset schedule
  51. LastTrafficResetTime int64 `json:"lastTrafficResetTime" form:"lastTrafficResetTime" gorm:"default:0"` // Last traffic reset timestamp
  52. ClientStats []xray.ClientTraffic `gorm:"foreignKey:InboundId;references:Id" json:"clientStats" form:"clientStats"` // Client traffic statistics
  53. // Xray configuration fields
  54. Listen string `json:"listen" form:"listen"`
  55. Port int `json:"port" form:"port" validate:"gte=0,lte=65535" example:"443"`
  56. Protocol Protocol `json:"protocol" form:"protocol" validate:"required,oneof=vmess vless trojan shadowsocks wireguard hysteria http mixed tunnel tun mtproto" example:"vless"`
  57. Settings string `json:"settings" form:"settings"`
  58. StreamSettings string `json:"streamSettings" form:"streamSettings"`
  59. Tag string `json:"tag" form:"tag" gorm:"unique" example:"in-443-tcp"`
  60. Sniffing string `json:"sniffing" form:"sniffing"`
  61. NodeID *int `json:"nodeId,omitempty" form:"nodeId" gorm:"index"`
  62. ShareAddrStrategy string `json:"shareAddrStrategy" form:"shareAddrStrategy" gorm:"column:share_addr_strategy;default:node" validate:"omitempty,oneof=node listen custom"`
  63. ShareAddr string `json:"shareAddr" form:"shareAddr" gorm:"column:share_addr"`
  64. // OriginNodeGuid is the panelGuid of the node that physically hosts this
  65. // inbound, propagated up across hops (#4983). Empty for an inbound that
  66. // lives on this panel's own xray; set to the originating node's GUID when
  67. // the inbound was synced from a node (kept as-is across further hops). Lets
  68. // the master attribute a deeply nested inbound to the real node instead of
  69. // the intermediate one it was fetched through.
  70. OriginNodeGuid string `json:"originNodeGuid,omitempty" form:"originNodeGuid" gorm:"column:origin_node_guid;index"`
  71. // FallbackParent is populated by the API layer when this inbound is
  72. // attached as a fallback child of a VLESS/Trojan TCP-TLS master.
  73. // The frontend uses it to rewrite client-share links so they advertise
  74. // the master's externally reachable endpoint instead of the child's
  75. // loopback listen. Not persisted.
  76. FallbackParent *FallbackParentInfo `json:"fallbackParent,omitempty" gorm:"-"`
  77. }
  78. // FallbackParentInfo carries everything the frontend needs to rewrite a
  79. // child inbound's client link: where to connect (the master's address
  80. // and port) and which path matched on the master's fallbacks array.
  81. // The frontend already has the master inbound in its dbInbounds list,
  82. // so we only ship identifiers + the match path here.
  83. type FallbackParentInfo struct {
  84. MasterId int `json:"masterId"`
  85. Path string `json:"path,omitempty"`
  86. }
  87. // OutboundTraffics tracks traffic statistics for Xray outbound connections.
  88. type OutboundTraffics struct {
  89. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
  90. Tag string `json:"tag" form:"tag" gorm:"unique"`
  91. Up int64 `json:"up" form:"up" gorm:"default:0"`
  92. Down int64 `json:"down" form:"down" gorm:"default:0"`
  93. Total int64 `json:"total" form:"total" gorm:"default:0"`
  94. }
  95. // InboundClientIps stores IP addresses associated with inbound clients for access control.
  96. type InboundClientIps struct {
  97. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  98. ClientEmail string `json:"clientEmail" form:"clientEmail" gorm:"unique"`
  99. Ips string `json:"ips" form:"ips"`
  100. }
  101. // MarshalJSON emits the Ips column as a real JSON array instead of an escaped
  102. // JSON-text string. Empty or unparseable storage renders as null so API
  103. // consumers don't have to special-case the legacy double-encoded shape.
  104. func (ic InboundClientIps) MarshalJSON() ([]byte, error) {
  105. type alias InboundClientIps
  106. return json.Marshal(struct {
  107. alias
  108. Ips json.RawMessage `json:"ips"`
  109. }{
  110. alias: alias(ic),
  111. Ips: jsonStringFieldToRaw(ic.Ips),
  112. })
  113. }
  114. // UnmarshalJSON accepts ips as either a JSON array (modern shape) or a
  115. // JSON-encoded string (legacy shape), normalising back to the JSON-text the
  116. // column stores.
  117. func (ic *InboundClientIps) UnmarshalJSON(data []byte) error {
  118. type alias InboundClientIps
  119. aux := struct {
  120. *alias
  121. Ips json.RawMessage `json:"ips"`
  122. }{
  123. alias: (*alias)(ic),
  124. }
  125. if err := json.Unmarshal(data, &aux); err != nil {
  126. return err
  127. }
  128. ic.Ips = jsonStringFieldFromRaw(aux.Ips)
  129. return nil
  130. }
  131. // HistoryOfSeeders tracks which database seeders have been executed to prevent re-running.
  132. type HistoryOfSeeders struct {
  133. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  134. SeederName string `json:"seederName"`
  135. }
  136. // ApiTokenUnixMillisecondsThreshold separates legacy millisecond timestamps
  137. // from the seconds-based API token timestamp contract.
  138. const ApiTokenUnixMillisecondsThreshold int64 = 100_000_000_000
  139. type ApiToken struct {
  140. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  141. Name string `json:"name" gorm:"uniqueIndex;not null"`
  142. Token string `json:"token" gorm:"not null"` // SHA-256 hash; the plaintext is shown only once at creation
  143. Enabled bool `json:"enabled" gorm:"default:true"`
  144. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime"`
  145. }
  146. // MarshalJSON emits settings, streamSettings, and sniffing as nested JSON
  147. // objects rather than escaped strings, so API consumers don't need to JSON.parse
  148. // a string inside a string. Empty fields render as null; fields whose stored
  149. // text isn't valid JSON fall back to a JSON-encoded string so no data is lost.
  150. func (i Inbound) MarshalJSON() ([]byte, error) {
  151. type alias Inbound
  152. return json.Marshal(struct {
  153. alias
  154. Settings json.RawMessage `json:"settings"`
  155. StreamSettings json.RawMessage `json:"streamSettings"`
  156. Sniffing json.RawMessage `json:"sniffing"`
  157. }{
  158. alias: alias(i),
  159. Settings: jsonStringFieldToRaw(i.Settings),
  160. StreamSettings: jsonStringFieldToRaw(i.StreamSettings),
  161. Sniffing: jsonStringFieldToRaw(i.Sniffing),
  162. })
  163. }
  164. // UnmarshalJSON accepts settings, streamSettings, and sniffing as either a raw
  165. // JSON object/array (the modern shape MarshalJSON emits) or a JSON-encoded
  166. // string (the legacy shape). Either form is normalised back to the JSON-text
  167. // string the DB column stores.
  168. func (i *Inbound) UnmarshalJSON(data []byte) error {
  169. type alias Inbound
  170. aux := struct {
  171. *alias
  172. Settings json.RawMessage `json:"settings"`
  173. StreamSettings json.RawMessage `json:"streamSettings"`
  174. Sniffing json.RawMessage `json:"sniffing"`
  175. }{
  176. alias: (*alias)(i),
  177. }
  178. if err := json.Unmarshal(data, &aux); err != nil {
  179. return err
  180. }
  181. i.Settings = jsonStringFieldFromRaw(aux.Settings)
  182. i.StreamSettings = jsonStringFieldFromRaw(aux.StreamSettings)
  183. i.Sniffing = jsonStringFieldFromRaw(aux.Sniffing)
  184. return nil
  185. }
  186. func jsonStringFieldToRaw(s string) json.RawMessage {
  187. trimmed := strings.TrimSpace(s)
  188. if trimmed == "" {
  189. return json.RawMessage("null")
  190. }
  191. if json.Valid([]byte(trimmed)) {
  192. return json.RawMessage(trimmed)
  193. }
  194. b, _ := json.Marshal(s)
  195. return b
  196. }
  197. func jsonStringFieldFromRaw(r json.RawMessage) string {
  198. trimmed := bytes.TrimSpace(r)
  199. if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {
  200. return ""
  201. }
  202. if trimmed[0] == '"' {
  203. var s string
  204. if err := json.Unmarshal(trimmed, &s); err == nil {
  205. return s
  206. }
  207. }
  208. return string(trimmed)
  209. }
  210. // StripInboundXhttpClientFields removes xHTTP knobs that belong on the
  211. // client dialer and subscription share-link extras only. xray-core's XHTTP
  212. // inbound listener does not consume them; the panel still stores them on
  213. // the inbound row so buildXhttpExtra can push defaults to clients.
  214. func StripInboundXhttpClientFields(streamSettings string) (string, bool) {
  215. if streamSettings == "" {
  216. return streamSettings, false
  217. }
  218. var stream map[string]any
  219. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  220. return streamSettings, false
  221. }
  222. if stream["network"] != "xhttp" {
  223. return streamSettings, false
  224. }
  225. xhttp, ok := stream["xhttpSettings"].(map[string]any)
  226. if !ok || len(xhttp) == 0 {
  227. return streamSettings, false
  228. }
  229. clientOnly := []string{
  230. "xmux",
  231. "downloadSettings",
  232. "scMinPostsIntervalMs",
  233. "uplinkChunkSize",
  234. "noGRPCHeader",
  235. }
  236. changed := false
  237. for _, key := range clientOnly {
  238. if _, has := xhttp[key]; has {
  239. delete(xhttp, key)
  240. changed = true
  241. }
  242. }
  243. if !changed {
  244. return streamSettings, false
  245. }
  246. out, err := json.MarshalIndent(stream, "", " ")
  247. if err != nil {
  248. return streamSettings, false
  249. }
  250. return string(out), true
  251. }
  252. // GenXrayInboundConfig generates an Xray inbound configuration from the Inbound model.
  253. func (i *Inbound) GenXrayInboundConfig() *xray.InboundConfig {
  254. listen := i.Listen
  255. if listen == "" {
  256. listen = "0.0.0.0"
  257. }
  258. listen = fmt.Sprintf("\"%v\"", listen)
  259. protocol := string(i.Protocol)
  260. settings := i.Settings
  261. switch i.Protocol {
  262. case Shadowsocks:
  263. if healed, ok := HealShadowsocksClientMethods(settings); ok {
  264. settings = healed
  265. }
  266. case VMESS:
  267. if stripped, ok := StripVmessClientSecurity(settings); ok {
  268. settings = stripped
  269. }
  270. case VLESS:
  271. if stripped, ok := StripVlessInboundEncryption(settings); ok {
  272. settings = stripped
  273. }
  274. }
  275. streamSettings := i.StreamSettings
  276. if stripped, ok := StripInboundXhttpClientFields(streamSettings); ok {
  277. streamSettings = stripped
  278. }
  279. return &xray.InboundConfig{
  280. Listen: json_util.RawMessage(listen),
  281. Port: i.Port,
  282. Protocol: protocol,
  283. Settings: json_util.RawMessage(settings),
  284. StreamSettings: json_util.RawMessage(streamSettings),
  285. Tag: i.Tag,
  286. Sniffing: json_util.RawMessage(i.Sniffing),
  287. }
  288. }
  289. func StripVmessClientSecurity(settings string) (string, bool) {
  290. if settings == "" {
  291. return settings, false
  292. }
  293. var parsed map[string]any
  294. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  295. return settings, false
  296. }
  297. clients, ok := parsed["clients"].([]any)
  298. if !ok {
  299. return settings, false
  300. }
  301. changed := false
  302. for i := range clients {
  303. cm, ok := clients[i].(map[string]any)
  304. if !ok {
  305. continue
  306. }
  307. if _, has := cm["security"]; has {
  308. delete(cm, "security")
  309. clients[i] = cm
  310. changed = true
  311. }
  312. }
  313. if !changed {
  314. return settings, false
  315. }
  316. out, err := json.MarshalIndent(parsed, "", " ")
  317. if err != nil {
  318. return settings, false
  319. }
  320. return string(out), true
  321. }
  322. func StripVlessInboundEncryption(settings string) (string, bool) {
  323. if settings == "" {
  324. return settings, false
  325. }
  326. var parsed map[string]any
  327. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  328. return settings, false
  329. }
  330. if _, has := parsed["encryption"]; !has {
  331. return settings, false
  332. }
  333. delete(parsed, "encryption")
  334. out, err := json.MarshalIndent(parsed, "", " ")
  335. if err != nil {
  336. return settings, false
  337. }
  338. return string(out), true
  339. }
  340. // HealShadowsocksClientMethods normalises the per-client `method` field
  341. // on a shadowsocks inbound's settings JSON before it leaves for xray-core:
  342. // - Legacy ciphers (aes-*, chacha20-*): every client must carry a
  343. // per-user `method` matching the inbound's top-level method, otherwise
  344. // xray fails with "unsupported cipher method:".
  345. // - Shadowsocks 2022 (2022-blake3-*): xray's multi-user code rejects the
  346. // inbound with "users must have empty method" when a client carries
  347. // one — strip stale entries left over from a switch off a legacy
  348. // cipher.
  349. //
  350. // Returns the rewritten settings string and true when anything changed.
  351. func HealShadowsocksClientMethods(settings string) (string, bool) {
  352. if settings == "" {
  353. return settings, false
  354. }
  355. var parsed map[string]any
  356. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  357. return settings, false
  358. }
  359. method, _ := parsed["method"].(string)
  360. clients, ok := parsed["clients"].([]any)
  361. if !ok {
  362. return settings, false
  363. }
  364. is2022 := strings.HasPrefix(method, "2022-blake3-")
  365. changed := false
  366. for i := range clients {
  367. cm, ok := clients[i].(map[string]any)
  368. if !ok {
  369. continue
  370. }
  371. if is2022 {
  372. if _, hasKey := cm["method"]; hasKey {
  373. delete(cm, "method")
  374. clients[i] = cm
  375. changed = true
  376. }
  377. continue
  378. }
  379. if method == "" {
  380. continue
  381. }
  382. existing, _ := cm["method"].(string)
  383. if existing == method {
  384. continue
  385. }
  386. cm["method"] = method
  387. clients[i] = cm
  388. changed = true
  389. }
  390. if !changed {
  391. return settings, false
  392. }
  393. out, err := json.MarshalIndent(parsed, "", " ")
  394. if err != nil {
  395. return settings, false
  396. }
  397. return string(out), true
  398. }
  399. // GenerateFakeTLSSecret builds an MTProto FakeTLS secret for the given domain:
  400. // the "ee" FakeTLS marker, 16 random bytes, then the domain encoded as hex.
  401. // This single value is what mtg's config and the client tg:// link both use.
  402. func GenerateFakeTLSSecret(domain string) string {
  403. return "ee" + mtprotoRandomMiddle() + hex.EncodeToString([]byte(domain))
  404. }
  405. func mtprotoRandomMiddle() string {
  406. buf := make([]byte, 16)
  407. if _, err := rand.Read(buf); err != nil {
  408. panic(fmt.Errorf("mtproto: crypto/rand read failed: %w", err))
  409. }
  410. return hex.EncodeToString(buf)
  411. }
  412. // mtprotoSecretMiddle returns the 16-byte random middle of an existing secret
  413. // when it is well-formed, otherwise a freshly generated one. Reusing the middle
  414. // keeps the secret stable when only the FakeTLS domain changes.
  415. func mtprotoSecretMiddle(secret string) string {
  416. s := secret
  417. if strings.HasPrefix(s, "ee") || strings.HasPrefix(s, "dd") {
  418. s = s[2:]
  419. }
  420. if len(s) >= 32 {
  421. mid := s[:32]
  422. if _, err := hex.DecodeString(mid); err == nil {
  423. return mid
  424. }
  425. }
  426. return mtprotoRandomMiddle()
  427. }
  428. // HealMtprotoSecret normalises an mtproto inbound's settings JSON before the
  429. // value leaves for the mtg sidecar or a share link: it rebuilds `secret` so it
  430. // is always a valid FakeTLS secret whose trailing domain matches
  431. // `fakeTlsDomain`, generating the random middle when one is missing and
  432. // rewriting the domain suffix when the domain changed. Returns the rewritten
  433. // settings and true when anything changed.
  434. func HealMtprotoSecret(settings string) (string, bool) {
  435. if settings == "" {
  436. return settings, false
  437. }
  438. var parsed map[string]any
  439. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  440. return settings, false
  441. }
  442. domain, _ := parsed["fakeTlsDomain"].(string)
  443. domain = strings.TrimSpace(domain)
  444. if domain == "" {
  445. return settings, false
  446. }
  447. secret, _ := parsed["secret"].(string)
  448. expected := "ee" + mtprotoSecretMiddle(secret) + hex.EncodeToString([]byte(domain))
  449. if secret == expected {
  450. return settings, false
  451. }
  452. parsed["secret"] = expected
  453. out, err := json.MarshalIndent(parsed, "", " ")
  454. if err != nil {
  455. return settings, false
  456. }
  457. return string(out), true
  458. }
  459. // Setting stores key-value configuration settings for the 3x-ui panel.
  460. type Setting struct {
  461. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
  462. Key string `json:"key" form:"key" gorm:"index:idx_settings_key"`
  463. Value string `json:"value" form:"value"`
  464. }
  465. // Node represents a remote 3x-ui panel registered with the central panel.
  466. // The central panel polls each node's existing /panel/api/server/status
  467. // endpoint over HTTP using the per-node ApiToken to populate the runtime
  468. // status fields below.
  469. type Node struct {
  470. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement" example:"1"`
  471. Name string `json:"name" form:"name" gorm:"uniqueIndex" validate:"required" example:"de-fra-1"`
  472. Remark string `json:"remark" form:"remark"`
  473. Scheme string `json:"scheme" form:"scheme" validate:"omitempty,oneof=http https" example:"https"`
  474. Address string `json:"address" form:"address" validate:"required" example:"node1.example.com"`
  475. Port int `json:"port" form:"port" validate:"gte=1,lte=65535" example:"2053"`
  476. BasePath string `json:"basePath" form:"basePath" example:"/"`
  477. ApiToken string `json:"apiToken" form:"apiToken" validate:"required_unless=TlsVerifyMode mtls" example:"abcdef0123456789"`
  478. Enable bool `json:"enable" form:"enable" gorm:"default:true" example:"true"`
  479. AllowPrivateAddress bool `json:"allowPrivateAddress" form:"allowPrivateAddress" gorm:"default:false"`
  480. TlsVerifyMode string `json:"tlsVerifyMode" form:"tlsVerifyMode" gorm:"column:tls_verify_mode;default:verify" validate:"omitempty,oneof=verify skip pin mtls"`
  481. PinnedCertSha256 string `json:"pinnedCertSha256" form:"pinnedCertSha256" gorm:"column:pinned_cert_sha256"`
  482. InboundSyncMode string `json:"inboundSyncMode" form:"inboundSyncMode" gorm:"column:inbound_sync_mode;default:all" validate:"omitempty,oneof=all selected"`
  483. InboundTags []string `json:"inboundTags" form:"inboundTags" gorm:"serializer:json;column:inbound_tags"`
  484. OutboundTag string `json:"outboundTag" form:"outboundTag" gorm:"column:outbound_tag"`
  485. // Guid is the remote panel's stable self-identifier (its panelGuid),
  486. // learned from each heartbeat. It is the globally stable node identity used
  487. // to attribute online clients/inbounds to the physical node across a chain
  488. // of nodes (#4983); panel-local autoincrement ids don't survive a hop.
  489. // Observed-state only — never user-edited.
  490. Guid string `json:"guid" gorm:"column:guid;index"`
  491. // Heartbeat-updated fields. UpdatedAt advances on every probe even when
  492. // the row is otherwise unchanged so the UI's "last seen" tooltip is
  493. // truthful without us having to read LastHeartbeat separately.
  494. Status string `json:"status" gorm:"default:unknown" example:"online"` // online|offline|unknown
  495. LastHeartbeat int64 `json:"lastHeartbeat" example:"1700000000"` // unix seconds, 0 = never
  496. LatencyMs int `json:"latencyMs" example:"42"`
  497. XrayVersion string `json:"xrayVersion" example:"25.10.31"`
  498. PanelVersion string `json:"panelVersion" gorm:"column:panel_version" example:"v3.x.x"`
  499. CpuPct float64 `json:"cpuPct" example:"23.5"`
  500. MemPct float64 `json:"memPct" example:"45.1"`
  501. UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
  502. NetUp uint64 `json:"netUp" gorm:"column:net_up" example:"1048576"`
  503. NetDown uint64 `json:"netDown" gorm:"column:net_down" example:"2097152"`
  504. LastError string `json:"lastError"`
  505. // XrayState and XrayError are captured from the remote node's /panel/api/server/status
  506. // during heartbeats. They let the central panel distinguish "panel API reachable"
  507. // (status=online) from "Xray core itself has failed on the node" for monitoring.
  508. XrayState string `json:"xrayState" gorm:"column:xray_state"`
  509. XrayError string `json:"xrayError" gorm:"column:xray_error"`
  510. ConfigDirty bool `json:"configDirty" gorm:"default:false"`
  511. ConfigDirtyAt int64 `json:"configDirtyAt"`
  512. InboundCount int `json:"inboundCount" gorm:"-" example:"5"`
  513. ClientCount int `json:"clientCount" gorm:"-" example:"27"`
  514. OnlineCount int `json:"onlineCount" gorm:"-" example:"3"`
  515. ActiveCount int `json:"activeCount" gorm:"-" example:"23"`
  516. DisabledCount int `json:"disabledCount" gorm:"-" example:"3"`
  517. DepletedCount int `json:"depletedCount" gorm:"-" example:"1"`
  518. // ParentGuid + Transitive are set only when a node is surfaced as part of a
  519. // node tree (#4983): direct nodes carry the master panel's own GUID, a
  520. // transitive sub-node carries its parent node's GUID. Transitive nodes are
  521. // read-only projections (Id == 0, not persisted) — never edited or deployed.
  522. ParentGuid string `json:"parentGuid,omitempty" gorm:"-"`
  523. Transitive bool `json:"transitive,omitempty" gorm:"-"`
  524. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli" example:"1700000000"`
  525. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli" example:"1700000000"`
  526. }
  527. // NodeSummary is the read-only identity of a node as published one hop up: the
  528. // view a panel exposes about the nodes it directly manages, so a master can
  529. // surface transitive sub-nodes in a chained topology (#4983). Counts are
  530. // computed by the consuming master from its own per-GUID data, never trusted
  531. // from the child, so this carries identity/health only.
  532. type NodeSummary struct {
  533. Guid string `json:"guid"`
  534. ParentGuid string `json:"parentGuid"`
  535. Name string `json:"name"`
  536. Address string `json:"address"`
  537. Scheme string `json:"scheme"`
  538. Port int `json:"port"`
  539. Status string `json:"status"`
  540. LastHeartbeat int64 `json:"lastHeartbeat"`
  541. LatencyMs int `json:"latencyMs"`
  542. PanelVersion string `json:"panelVersion"`
  543. XrayVersion string `json:"xrayVersion"`
  544. // XrayState/XrayError forwarded so masters can surface xray failure on transitive sub-nodes too.
  545. XrayState string `json:"xrayState"`
  546. XrayError string `json:"xrayError,omitempty"`
  547. }
  548. type ClientReverse struct {
  549. Tag string `json:"tag"`
  550. }
  551. // Client represents a client configuration for Xray inbounds with traffic limits and settings.
  552. type Client struct {
  553. ID string `json:"id,omitempty"` // Unique client identifier
  554. Security string `json:"security"` // Security method (e.g., "auto", "aes-128-gcm")
  555. Password string `json:"password,omitempty"` // Client password
  556. Flow string `json:"flow,omitempty"` // Flow control (XTLS)
  557. Reverse *ClientReverse `json:"reverse,omitempty"` // VLESS simple reverse proxy settings
  558. Auth string `json:"auth,omitempty"` // Auth password (Hysteria)
  559. Email string `json:"email"` // Client email identifier
  560. LimitIP int `json:"limitIp"` // IP limit for this client
  561. TotalGB int64 `json:"totalGB" form:"totalGB"` // Total traffic limit in GB
  562. ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` // Expiration timestamp
  563. Enable bool `json:"enable" form:"enable"` // Whether the client is enabled
  564. TgID int64 `json:"tgId" form:"tgId"` // Telegram user ID for notifications
  565. SubID string `json:"subId" form:"subId"` // Subscription identifier
  566. Group string `json:"group,omitempty" form:"group"` // Logical grouping label
  567. Comment string `json:"comment" form:"comment"` // Client comment
  568. Reset int `json:"reset" form:"reset"` // Reset period in days
  569. CreatedAt int64 `json:"created_at,omitempty"` // Creation timestamp
  570. UpdatedAt int64 `json:"updated_at,omitempty"` // Last update timestamp
  571. }
  572. type ClientRecord struct {
  573. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  574. Email string `json:"email" gorm:"uniqueIndex;not null"`
  575. SubID string `json:"subId" gorm:"index;column:sub_id"`
  576. UUID string `json:"uuid" gorm:"column:uuid"`
  577. Password string `json:"password"`
  578. Auth string `json:"auth"`
  579. Flow string `json:"flow"`
  580. Security string `json:"security"`
  581. Reverse string `json:"reverse" gorm:"column:reverse"`
  582. LimitIP int `json:"limitIp" gorm:"column:limit_ip"`
  583. TotalGB int64 `json:"totalGB" gorm:"column:total_gb"`
  584. ExpiryTime int64 `json:"expiryTime" gorm:"column:expiry_time"`
  585. Enable bool `json:"enable" gorm:"default:true"`
  586. TgID int64 `json:"tgId" gorm:"column:tg_id"`
  587. Group string `json:"group" gorm:"column:group_name;default:'';index:idx_client_record_group"`
  588. Comment string `json:"comment"`
  589. Reset int `json:"reset" gorm:"default:0"`
  590. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  591. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  592. }
  593. func (ClientRecord) TableName() string { return "clients" }
  594. type ClientGroup struct {
  595. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  596. Name string `json:"name" gorm:"uniqueIndex;not null"`
  597. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  598. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  599. }
  600. func (ClientGroup) TableName() string { return "client_groups" }
  601. // MarshalJSON emits the reverse column as a nested JSON object rather than an
  602. // escaped JSON-text string, matching the same convention Inbound uses for its
  603. // JSON-text columns. Empty storage renders as null.
  604. func (r ClientRecord) MarshalJSON() ([]byte, error) {
  605. type alias ClientRecord
  606. return json.Marshal(struct {
  607. alias
  608. Reverse json.RawMessage `json:"reverse"`
  609. }{
  610. alias: alias(r),
  611. Reverse: jsonStringFieldToRaw(r.Reverse),
  612. })
  613. }
  614. // UnmarshalJSON accepts reverse as either a JSON object (modern shape) or a
  615. // JSON-encoded string (legacy shape).
  616. func (r *ClientRecord) UnmarshalJSON(data []byte) error {
  617. type alias ClientRecord
  618. aux := struct {
  619. *alias
  620. Reverse json.RawMessage `json:"reverse"`
  621. }{
  622. alias: (*alias)(r),
  623. }
  624. if err := json.Unmarshal(data, &aux); err != nil {
  625. return err
  626. }
  627. r.Reverse = jsonStringFieldFromRaw(aux.Reverse)
  628. return nil
  629. }
  630. type ClientInbound struct {
  631. ClientId int `json:"clientId" gorm:"primaryKey;column:client_id;index"`
  632. InboundId int `json:"inboundId" gorm:"primaryKey;column:inbound_id;index"`
  633. FlowOverride string `json:"flowOverride" gorm:"column:flow_override"`
  634. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  635. }
  636. func (ClientInbound) TableName() string { return "client_inbounds" }
  637. // ClientExternalLink is a per-client entry surfaced in the client's
  638. // subscription. Two kinds:
  639. // - "link": a single third-party share link (vless://, vmess://, trojan://,
  640. // ss://, hysteria2://, wireguard://). Emitted verbatim in raw subs; parsed
  641. // into an outbound/proxy for JSON and Clash.
  642. // - "subscription": a remote subscription URL. The panel fetches it (cached),
  643. // decodes its links, and merges them into the client's subscription.
  644. type ClientExternalLink struct {
  645. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  646. ClientId int `json:"clientId" gorm:"index;column:client_id"`
  647. Kind string `json:"kind" gorm:"column:kind"`
  648. Value string `json:"value" gorm:"column:value"`
  649. Remark string `json:"remark" gorm:"column:remark"`
  650. SortIndex int `json:"sortIndex" gorm:"column:sort_index"`
  651. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  652. }
  653. func (ClientExternalLink) TableName() string { return "client_external_links" }
  654. // External link kinds.
  655. const (
  656. ExternalLinkKindLink = "link"
  657. ExternalLinkKindSubscription = "subscription"
  658. )
  659. type InboundFallback struct {
  660. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  661. MasterId int `json:"masterId" gorm:"index;not null;column:master_id"`
  662. ChildId int `json:"childId" gorm:"index;not null;column:child_id"`
  663. Name string `json:"name"`
  664. Alpn string `json:"alpn"`
  665. Path string `json:"path"`
  666. Dest string `json:"dest"`
  667. Xver int `json:"xver"`
  668. SortOrder int `json:"sortOrder" gorm:"default:0;column:sort_order"`
  669. }
  670. func (InboundFallback) TableName() string { return "inbound_fallbacks" }
  671. // Host is an override endpoint attached to an inbound: at subscription time each
  672. // enabled host renders one share link/proxy with its own address/port/TLS/etc.,
  673. // superseding the legacy externalProxy array. Free-JSON fields are stored as
  674. // text and parsed in the sub layer; slice fields use the json serializer.
  675. type Host struct {
  676. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement" example:"1"`
  677. InboundId int `json:"inboundId" form:"inboundId" gorm:"index;not null;column:inbound_id" validate:"required" example:"1"`
  678. SortOrder int `json:"sortOrder" form:"sortOrder" gorm:"default:0;column:sort_order"`
  679. Remark string `json:"remark" form:"remark" validate:"required,max=256" example:"cdn-front"`
  680. ServerDescription string `json:"serverDescription" form:"serverDescription" gorm:"column:server_description" validate:"omitempty,max=64"`
  681. IsDisabled bool `json:"isDisabled" form:"isDisabled" gorm:"default:false;column:is_disabled"`
  682. IsHidden bool `json:"isHidden" form:"isHidden" gorm:"default:false;column:is_hidden"`
  683. Tags []string `json:"tags" form:"tags" gorm:"serializer:json"`
  684. Address string `json:"address" form:"address" example:"cdn.example.com"`
  685. Port int `json:"port" form:"port" gorm:"default:0" validate:"gte=0,lte=65535" example:"8443"`
  686. Security string `json:"security" form:"security" gorm:"default:same" validate:"omitempty,oneof=same tls none reality" example:"same"`
  687. Sni string `json:"sni" form:"sni"`
  688. HostHeader string `json:"hostHeader" form:"hostHeader" gorm:"column:host_header"`
  689. Path string `json:"path" form:"path"`
  690. Alpn []string `json:"alpn" form:"alpn" gorm:"serializer:json"`
  691. Fingerprint string `json:"fingerprint" form:"fingerprint"`
  692. OverrideSniFromAddress bool `json:"overrideSniFromAddress" form:"overrideSniFromAddress" gorm:"column:override_sni_from_address"`
  693. KeepSniBlank bool `json:"keepSniBlank" form:"keepSniBlank" gorm:"column:keep_sni_blank"`
  694. PinnedPeerCertSha256 []string `json:"pinnedPeerCertSha256" form:"pinnedPeerCertSha256" gorm:"serializer:json;column:pinned_peer_cert_sha256"`
  695. VerifyPeerCertByName string `json:"verifyPeerCertByName" form:"verifyPeerCertByName" gorm:"column:verify_peer_cert_by_name"`
  696. AllowInsecure bool `json:"allowInsecure" form:"allowInsecure" gorm:"column:allow_insecure"`
  697. EchConfigList string `json:"echConfigList" form:"echConfigList" gorm:"column:ech_config_list"`
  698. MuxParams string `json:"muxParams" form:"muxParams" gorm:"type:text;column:mux_params"`
  699. SockoptParams string `json:"sockoptParams" form:"sockoptParams" gorm:"type:text;column:sockopt_params"`
  700. // FinalMask is a JSON object of xray finalmask masks (tcp/udp/quicParams),
  701. // merged into this host's JSON-subscription stream. Empty = no override.
  702. FinalMask string `json:"finalMask" form:"finalMask" gorm:"type:text;column:final_mask"`
  703. // VlessRoute is a free-form port/range routing spec (e.g. "53,443,1000-2000");
  704. // stored verbatim, format-validated on the frontend.
  705. VlessRoute string `json:"vlessRoute" form:"vlessRoute" gorm:"column:vless_route"`
  706. ExcludeFromSubTypes []string `json:"excludeFromSubTypes" form:"excludeFromSubTypes" gorm:"serializer:json;column:exclude_from_sub_types"`
  707. MihomoIpVersion string `json:"mihomoIpVersion" form:"mihomoIpVersion" gorm:"column:mihomo_ip_version" validate:"omitempty,oneof=dual ipv4 ipv6 ipv4-prefer ipv6-prefer"`
  708. MihomoX25519 bool `json:"mihomoX25519" form:"mihomoX25519" gorm:"column:mihomo_x25519"`
  709. ShuffleHost bool `json:"shuffleHost" form:"shuffleHost" gorm:"column:shuffle_host"`
  710. NodeGuids []string `json:"nodeGuids,omitempty" form:"nodeGuids" gorm:"serializer:json;column:node_guids"`
  711. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  712. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  713. }
  714. func (Host) TableName() string { return "hosts" }
  715. func (c *Client) ToRecord() *ClientRecord {
  716. rec := &ClientRecord{
  717. Email: c.Email,
  718. SubID: c.SubID,
  719. UUID: c.ID,
  720. Password: c.Password,
  721. Auth: c.Auth,
  722. Flow: c.Flow,
  723. Security: c.Security,
  724. LimitIP: c.LimitIP,
  725. TotalGB: c.TotalGB,
  726. ExpiryTime: c.ExpiryTime,
  727. Enable: c.Enable,
  728. TgID: c.TgID,
  729. Group: c.Group,
  730. Comment: c.Comment,
  731. Reset: c.Reset,
  732. CreatedAt: c.CreatedAt,
  733. UpdatedAt: c.UpdatedAt,
  734. }
  735. if c.Reverse != nil {
  736. if b, err := json.Marshal(c.Reverse); err == nil {
  737. rec.Reverse = string(b)
  738. }
  739. }
  740. return rec
  741. }
  742. func (r *ClientRecord) ToClient() *Client {
  743. c := &Client{
  744. ID: r.UUID,
  745. Email: r.Email,
  746. SubID: r.SubID,
  747. Password: r.Password,
  748. Auth: r.Auth,
  749. Flow: r.Flow,
  750. Security: r.Security,
  751. LimitIP: r.LimitIP,
  752. TotalGB: r.TotalGB,
  753. ExpiryTime: r.ExpiryTime,
  754. Enable: r.Enable,
  755. TgID: r.TgID,
  756. Group: r.Group,
  757. Comment: r.Comment,
  758. Reset: r.Reset,
  759. CreatedAt: r.CreatedAt,
  760. UpdatedAt: r.UpdatedAt,
  761. }
  762. if r.Reverse != "" {
  763. var rev ClientReverse
  764. if err := json.Unmarshal([]byte(r.Reverse), &rev); err == nil {
  765. c.Reverse = &rev
  766. }
  767. }
  768. return c
  769. }
  770. type ClientMergeConflict struct {
  771. Field string
  772. Old any
  773. New any
  774. Kept any
  775. }
  776. type OutboundSubscription struct {
  777. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
  778. Remark string `json:"remark" form:"remark"`
  779. Url string `json:"url" form:"url"`
  780. Enabled bool `json:"enabled" form:"enabled" gorm:"default:true"`
  781. AllowPrivate bool `json:"allowPrivate" form:"allowPrivate" gorm:"default:false"`
  782. TagPrefix string `json:"tagPrefix" form:"tagPrefix"`
  783. UpdateInterval int `json:"updateInterval" form:"updateInterval" gorm:"default:600"` // seconds between refreshes
  784. Priority int `json:"priority" form:"priority" gorm:"default:0"` // order among subscriptions in the merged outbounds (lower = earlier)
  785. Prepend bool `json:"prepend" form:"prepend" gorm:"default:false"` // place this subscription's outbounds before the manual template outbounds
  786. LastUpdated int64 `json:"lastUpdated" form:"lastUpdated"`
  787. LastError string `json:"lastError" form:"lastError"`
  788. LastFetchedOutbounds string `json:"lastFetchedOutbounds" form:"lastFetchedOutbounds" gorm:"type:text"`
  789. LinkIdentities string `json:"-" gorm:"type:text;column:link_identities"`
  790. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  791. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  792. OutboundCount int `json:"outboundCount" gorm:"-"`
  793. }
  794. func MergeClientRecord(existing *ClientRecord, incoming *ClientRecord) []ClientMergeConflict {
  795. var conflicts []ClientMergeConflict
  796. keep := func(field string, oldV, newV, kept any) {
  797. conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: oldV, New: newV, Kept: kept})
  798. }
  799. const redacted = "<redacted>"
  800. keepSecret := func(field string) {
  801. conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: redacted, New: redacted, Kept: redacted})
  802. }
  803. incomingNewer := incoming.UpdatedAt > existing.UpdatedAt ||
  804. (incoming.UpdatedAt == existing.UpdatedAt && incoming.CreatedAt > existing.CreatedAt)
  805. if existing.UUID != incoming.UUID && incoming.UUID != "" {
  806. if incomingNewer || existing.UUID == "" {
  807. existing.UUID = incoming.UUID
  808. }
  809. keepSecret("uuid")
  810. }
  811. if existing.Password != incoming.Password && incoming.Password != "" {
  812. if incomingNewer || existing.Password == "" {
  813. existing.Password = incoming.Password
  814. keepSecret("password")
  815. }
  816. }
  817. if existing.Auth != incoming.Auth && incoming.Auth != "" {
  818. if incomingNewer || existing.Auth == "" {
  819. existing.Auth = incoming.Auth
  820. keepSecret("auth")
  821. }
  822. }
  823. if existing.Flow != incoming.Flow && incoming.Flow != "" {
  824. if incomingNewer || existing.Flow == "" {
  825. keep("flow", existing.Flow, incoming.Flow, incoming.Flow)
  826. existing.Flow = incoming.Flow
  827. }
  828. }
  829. if existing.Security != incoming.Security && incoming.Security != "" {
  830. if incomingNewer || existing.Security == "" {
  831. keep("security", existing.Security, incoming.Security, incoming.Security)
  832. existing.Security = incoming.Security
  833. }
  834. }
  835. if existing.SubID != incoming.SubID && incoming.SubID != "" {
  836. if incomingNewer || existing.SubID == "" {
  837. existing.SubID = incoming.SubID
  838. keepSecret("subId")
  839. }
  840. }
  841. if existing.TotalGB != incoming.TotalGB {
  842. picked := existing.TotalGB
  843. if existing.TotalGB == 0 || (incoming.TotalGB != 0 && incoming.TotalGB > existing.TotalGB) {
  844. picked = incoming.TotalGB
  845. }
  846. if picked != existing.TotalGB {
  847. keep("totalGB", existing.TotalGB, incoming.TotalGB, picked)
  848. existing.TotalGB = picked
  849. }
  850. }
  851. if existing.ExpiryTime != incoming.ExpiryTime {
  852. picked := existing.ExpiryTime
  853. if existing.ExpiryTime == 0 || (incoming.ExpiryTime != 0 && incoming.ExpiryTime > existing.ExpiryTime) {
  854. picked = incoming.ExpiryTime
  855. }
  856. if picked != existing.ExpiryTime {
  857. keep("expiryTime", existing.ExpiryTime, incoming.ExpiryTime, picked)
  858. existing.ExpiryTime = picked
  859. }
  860. }
  861. if existing.LimitIP != incoming.LimitIP && incoming.LimitIP != 0 {
  862. picked := existing.LimitIP
  863. if existing.LimitIP == 0 || incoming.LimitIP > existing.LimitIP {
  864. picked = incoming.LimitIP
  865. }
  866. if picked != existing.LimitIP {
  867. keep("limitIp", existing.LimitIP, incoming.LimitIP, picked)
  868. existing.LimitIP = picked
  869. }
  870. }
  871. if existing.TgID != incoming.TgID && incoming.TgID != 0 {
  872. if incomingNewer || existing.TgID == 0 {
  873. keep("tgId", existing.TgID, incoming.TgID, incoming.TgID)
  874. existing.TgID = incoming.TgID
  875. }
  876. }
  877. if existing.Reset != incoming.Reset && incoming.Reset != 0 {
  878. if incomingNewer || existing.Reset == 0 {
  879. keep("reset", existing.Reset, incoming.Reset, incoming.Reset)
  880. existing.Reset = incoming.Reset
  881. }
  882. }
  883. if existing.Reverse != incoming.Reverse && incoming.Reverse != "" {
  884. if incomingNewer || existing.Reverse == "" {
  885. keep("reverse", existing.Reverse, incoming.Reverse, incoming.Reverse)
  886. existing.Reverse = incoming.Reverse
  887. }
  888. }
  889. if existing.Comment != incoming.Comment && incoming.Comment != "" {
  890. if incomingNewer || existing.Comment == "" {
  891. keep("comment", existing.Comment, incoming.Comment, incoming.Comment)
  892. existing.Comment = incoming.Comment
  893. }
  894. }
  895. if existing.Group != incoming.Group && incoming.Group != "" {
  896. if incomingNewer || existing.Group == "" {
  897. keep("group", existing.Group, incoming.Group, incoming.Group)
  898. existing.Group = incoming.Group
  899. }
  900. }
  901. if existing.Enable != incoming.Enable {
  902. if incoming.Enable {
  903. if !existing.Enable {
  904. keep("enable", existing.Enable, incoming.Enable, true)
  905. existing.Enable = true
  906. }
  907. }
  908. }
  909. if incoming.CreatedAt != 0 && (existing.CreatedAt == 0 || incoming.CreatedAt < existing.CreatedAt) {
  910. existing.CreatedAt = incoming.CreatedAt
  911. }
  912. if incoming.UpdatedAt > existing.UpdatedAt {
  913. existing.UpdatedAt = incoming.UpdatedAt
  914. }
  915. return conflicts
  916. }