model.go 34 KB

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