model.go 34 KB

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