model.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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. OutboundTag string `json:"outboundTag" form:"outboundTag" gorm:"column:outbound_tag"`
  436. // Guid is the remote panel's stable self-identifier (its panelGuid),
  437. // learned from each heartbeat. It is the globally stable node identity used
  438. // to attribute online clients/inbounds to the physical node across a chain
  439. // of nodes (#4983); panel-local autoincrement ids don't survive a hop.
  440. // Observed-state only — never user-edited.
  441. Guid string `json:"guid" gorm:"column:guid;index"`
  442. // Heartbeat-updated fields. UpdatedAt advances on every probe even when
  443. // the row is otherwise unchanged so the UI's "last seen" tooltip is
  444. // truthful without us having to read LastHeartbeat separately.
  445. Status string `json:"status" gorm:"default:unknown" example:"online"` // online|offline|unknown
  446. LastHeartbeat int64 `json:"lastHeartbeat" example:"1700000000"` // unix seconds, 0 = never
  447. LatencyMs int `json:"latencyMs" example:"42"`
  448. XrayVersion string `json:"xrayVersion" example:"25.10.31"`
  449. PanelVersion string `json:"panelVersion" gorm:"column:panel_version" example:"v3.x.x"`
  450. CpuPct float64 `json:"cpuPct" example:"23.5"`
  451. MemPct float64 `json:"memPct" example:"45.1"`
  452. UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
  453. LastError string `json:"lastError"`
  454. // XrayState and XrayError are captured from the remote node's /panel/api/server/status
  455. // during heartbeats. They let the central panel distinguish "panel API reachable"
  456. // (status=online) from "Xray core itself has failed on the node" for monitoring.
  457. XrayState string `json:"xrayState" gorm:"column:xray_state"`
  458. XrayError string `json:"xrayError" gorm:"column:xray_error"`
  459. ConfigDirty bool `json:"configDirty" gorm:"default:false"`
  460. ConfigDirtyAt int64 `json:"configDirtyAt"`
  461. InboundCount int `json:"inboundCount" gorm:"-" example:"5"`
  462. ClientCount int `json:"clientCount" gorm:"-" example:"27"`
  463. OnlineCount int `json:"onlineCount" gorm:"-" example:"3"`
  464. DepletedCount int `json:"depletedCount" gorm:"-" example:"1"`
  465. // ParentGuid + Transitive are set only when a node is surfaced as part of a
  466. // node tree (#4983): direct nodes carry the master panel's own GUID, a
  467. // transitive sub-node carries its parent node's GUID. Transitive nodes are
  468. // read-only projections (Id == 0, not persisted) — never edited or deployed.
  469. ParentGuid string `json:"parentGuid,omitempty" gorm:"-"`
  470. Transitive bool `json:"transitive,omitempty" gorm:"-"`
  471. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli" example:"1700000000"`
  472. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli" example:"1700000000"`
  473. }
  474. // NodeSummary is the read-only identity of a node as published one hop up: the
  475. // view a panel exposes about the nodes it directly manages, so a master can
  476. // surface transitive sub-nodes in a chained topology (#4983). Counts are
  477. // computed by the consuming master from its own per-GUID data, never trusted
  478. // from the child, so this carries identity/health only.
  479. type NodeSummary struct {
  480. Guid string `json:"guid"`
  481. ParentGuid string `json:"parentGuid"`
  482. Name string `json:"name"`
  483. Address string `json:"address"`
  484. Scheme string `json:"scheme"`
  485. Port int `json:"port"`
  486. Status string `json:"status"`
  487. LastHeartbeat int64 `json:"lastHeartbeat"`
  488. LatencyMs int `json:"latencyMs"`
  489. PanelVersion string `json:"panelVersion"`
  490. XrayVersion string `json:"xrayVersion"`
  491. // XrayState/XrayError forwarded so masters can surface xray failure on transitive sub-nodes too.
  492. XrayState string `json:"xrayState"`
  493. XrayError string `json:"xrayError,omitempty"`
  494. }
  495. type ClientReverse struct {
  496. Tag string `json:"tag"`
  497. }
  498. // Client represents a client configuration for Xray inbounds with traffic limits and settings.
  499. type Client struct {
  500. ID string `json:"id,omitempty"` // Unique client identifier
  501. Security string `json:"security"` // Security method (e.g., "auto", "aes-128-gcm")
  502. Password string `json:"password,omitempty"` // Client password
  503. Flow string `json:"flow,omitempty"` // Flow control (XTLS)
  504. Reverse *ClientReverse `json:"reverse,omitempty"` // VLESS simple reverse proxy settings
  505. Auth string `json:"auth,omitempty"` // Auth password (Hysteria)
  506. Email string `json:"email"` // Client email identifier
  507. LimitIP int `json:"limitIp"` // IP limit for this client
  508. TotalGB int64 `json:"totalGB" form:"totalGB"` // Total traffic limit in GB
  509. ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` // Expiration timestamp
  510. Enable bool `json:"enable" form:"enable"` // Whether the client is enabled
  511. TgID int64 `json:"tgId" form:"tgId"` // Telegram user ID for notifications
  512. SubID string `json:"subId" form:"subId"` // Subscription identifier
  513. Group string `json:"group,omitempty" form:"group"` // Logical grouping label
  514. Comment string `json:"comment" form:"comment"` // Client comment
  515. Reset int `json:"reset" form:"reset"` // Reset period in days
  516. CreatedAt int64 `json:"created_at,omitempty"` // Creation timestamp
  517. UpdatedAt int64 `json:"updated_at,omitempty"` // Last update timestamp
  518. }
  519. type ClientRecord struct {
  520. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  521. Email string `json:"email" gorm:"uniqueIndex;not null"`
  522. SubID string `json:"subId" gorm:"index;column:sub_id"`
  523. UUID string `json:"uuid" gorm:"column:uuid"`
  524. Password string `json:"password"`
  525. Auth string `json:"auth"`
  526. Flow string `json:"flow"`
  527. Security string `json:"security"`
  528. Reverse string `json:"reverse" gorm:"column:reverse"`
  529. LimitIP int `json:"limitIp" gorm:"column:limit_ip"`
  530. TotalGB int64 `json:"totalGB" gorm:"column:total_gb"`
  531. ExpiryTime int64 `json:"expiryTime" gorm:"column:expiry_time"`
  532. Enable bool `json:"enable" gorm:"default:true"`
  533. TgID int64 `json:"tgId" gorm:"column:tg_id"`
  534. Group string `json:"group" gorm:"column:group_name;default:'';index:idx_client_record_group"`
  535. Comment string `json:"comment"`
  536. Reset int `json:"reset" gorm:"default:0"`
  537. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  538. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  539. }
  540. func (ClientRecord) TableName() string { return "clients" }
  541. type ClientGroup struct {
  542. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  543. Name string `json:"name" gorm:"uniqueIndex;not null"`
  544. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  545. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  546. }
  547. func (ClientGroup) TableName() string { return "client_groups" }
  548. // MarshalJSON emits the reverse column as a nested JSON object rather than an
  549. // escaped JSON-text string, matching the same convention Inbound uses for its
  550. // JSON-text columns. Empty storage renders as null.
  551. func (r ClientRecord) MarshalJSON() ([]byte, error) {
  552. type alias ClientRecord
  553. return json.Marshal(struct {
  554. alias
  555. Reverse json.RawMessage `json:"reverse"`
  556. }{
  557. alias: alias(r),
  558. Reverse: jsonStringFieldToRaw(r.Reverse),
  559. })
  560. }
  561. // UnmarshalJSON accepts reverse as either a JSON object (modern shape) or a
  562. // JSON-encoded string (legacy shape).
  563. func (r *ClientRecord) UnmarshalJSON(data []byte) error {
  564. type alias ClientRecord
  565. aux := struct {
  566. *alias
  567. Reverse json.RawMessage `json:"reverse"`
  568. }{
  569. alias: (*alias)(r),
  570. }
  571. if err := json.Unmarshal(data, &aux); err != nil {
  572. return err
  573. }
  574. r.Reverse = jsonStringFieldFromRaw(aux.Reverse)
  575. return nil
  576. }
  577. type ClientInbound struct {
  578. ClientId int `json:"clientId" gorm:"primaryKey;column:client_id;index"`
  579. InboundId int `json:"inboundId" gorm:"primaryKey;column:inbound_id;index"`
  580. FlowOverride string `json:"flowOverride" gorm:"column:flow_override"`
  581. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  582. }
  583. func (ClientInbound) TableName() string { return "client_inbounds" }
  584. // ClientExternalLink is a per-client entry surfaced in the client's
  585. // subscription. Two kinds:
  586. // - "link": a single third-party share link (vless://, vmess://, trojan://,
  587. // ss://, hysteria2://, wireguard://). Emitted verbatim in raw subs; parsed
  588. // into an outbound/proxy for JSON and Clash.
  589. // - "subscription": a remote subscription URL. The panel fetches it (cached),
  590. // decodes its links, and merges them into the client's subscription.
  591. type ClientExternalLink struct {
  592. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  593. ClientId int `json:"clientId" gorm:"index;column:client_id"`
  594. Kind string `json:"kind" gorm:"column:kind"`
  595. Value string `json:"value" gorm:"column:value"`
  596. Remark string `json:"remark" gorm:"column:remark"`
  597. SortIndex int `json:"sortIndex" gorm:"column:sort_index"`
  598. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  599. }
  600. func (ClientExternalLink) TableName() string { return "client_external_links" }
  601. // External link kinds.
  602. const (
  603. ExternalLinkKindLink = "link"
  604. ExternalLinkKindSubscription = "subscription"
  605. )
  606. type InboundFallback struct {
  607. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  608. MasterId int `json:"masterId" gorm:"index;not null;column:master_id"`
  609. ChildId int `json:"childId" gorm:"index;not null;column:child_id"`
  610. Name string `json:"name"`
  611. Alpn string `json:"alpn"`
  612. Path string `json:"path"`
  613. Dest string `json:"dest"`
  614. Xver int `json:"xver"`
  615. SortOrder int `json:"sortOrder" gorm:"default:0;column:sort_order"`
  616. }
  617. func (InboundFallback) TableName() string { return "inbound_fallbacks" }
  618. func (c *Client) ToRecord() *ClientRecord {
  619. rec := &ClientRecord{
  620. Email: c.Email,
  621. SubID: c.SubID,
  622. UUID: c.ID,
  623. Password: c.Password,
  624. Auth: c.Auth,
  625. Flow: c.Flow,
  626. Security: c.Security,
  627. LimitIP: c.LimitIP,
  628. TotalGB: c.TotalGB,
  629. ExpiryTime: c.ExpiryTime,
  630. Enable: c.Enable,
  631. TgID: c.TgID,
  632. Group: c.Group,
  633. Comment: c.Comment,
  634. Reset: c.Reset,
  635. CreatedAt: c.CreatedAt,
  636. UpdatedAt: c.UpdatedAt,
  637. }
  638. if c.Reverse != nil {
  639. if b, err := json.Marshal(c.Reverse); err == nil {
  640. rec.Reverse = string(b)
  641. }
  642. }
  643. return rec
  644. }
  645. func (r *ClientRecord) ToClient() *Client {
  646. c := &Client{
  647. ID: r.UUID,
  648. Email: r.Email,
  649. SubID: r.SubID,
  650. Password: r.Password,
  651. Auth: r.Auth,
  652. Flow: r.Flow,
  653. Security: r.Security,
  654. LimitIP: r.LimitIP,
  655. TotalGB: r.TotalGB,
  656. ExpiryTime: r.ExpiryTime,
  657. Enable: r.Enable,
  658. TgID: r.TgID,
  659. Group: r.Group,
  660. Comment: r.Comment,
  661. Reset: r.Reset,
  662. CreatedAt: r.CreatedAt,
  663. UpdatedAt: r.UpdatedAt,
  664. }
  665. if r.Reverse != "" {
  666. var rev ClientReverse
  667. if err := json.Unmarshal([]byte(r.Reverse), &rev); err == nil {
  668. c.Reverse = &rev
  669. }
  670. }
  671. return c
  672. }
  673. type ClientMergeConflict struct {
  674. Field string
  675. Old any
  676. New any
  677. Kept any
  678. }
  679. type OutboundSubscription struct {
  680. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
  681. Remark string `json:"remark" form:"remark"`
  682. Url string `json:"url" form:"url"`
  683. Enabled bool `json:"enabled" form:"enabled" gorm:"default:true"`
  684. AllowPrivate bool `json:"allowPrivate" form:"allowPrivate" gorm:"default:false"`
  685. TagPrefix string `json:"tagPrefix" form:"tagPrefix"`
  686. UpdateInterval int `json:"updateInterval" form:"updateInterval" gorm:"default:600"` // seconds between refreshes
  687. Priority int `json:"priority" form:"priority" gorm:"default:0"` // order among subscriptions in the merged outbounds (lower = earlier)
  688. Prepend bool `json:"prepend" form:"prepend" gorm:"default:false"` // place this subscription's outbounds before the manual template outbounds
  689. LastUpdated int64 `json:"lastUpdated" form:"lastUpdated"`
  690. LastError string `json:"lastError" form:"lastError"`
  691. LastFetchedOutbounds string `json:"lastFetchedOutbounds" form:"lastFetchedOutbounds" gorm:"type:text"`
  692. LinkIdentities string `json:"-" gorm:"type:text;column:link_identities"`
  693. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  694. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  695. OutboundCount int `json:"outboundCount" gorm:"-"`
  696. }
  697. func MergeClientRecord(existing *ClientRecord, incoming *ClientRecord) []ClientMergeConflict {
  698. var conflicts []ClientMergeConflict
  699. keep := func(field string, oldV, newV, kept any) {
  700. conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: oldV, New: newV, Kept: kept})
  701. }
  702. const redacted = "<redacted>"
  703. keepSecret := func(field string) {
  704. conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: redacted, New: redacted, Kept: redacted})
  705. }
  706. incomingNewer := incoming.UpdatedAt > existing.UpdatedAt ||
  707. (incoming.UpdatedAt == existing.UpdatedAt && incoming.CreatedAt > existing.CreatedAt)
  708. if existing.UUID != incoming.UUID && incoming.UUID != "" {
  709. if incomingNewer || existing.UUID == "" {
  710. existing.UUID = incoming.UUID
  711. }
  712. keepSecret("uuid")
  713. }
  714. if existing.Password != incoming.Password && incoming.Password != "" {
  715. if incomingNewer || existing.Password == "" {
  716. existing.Password = incoming.Password
  717. keepSecret("password")
  718. }
  719. }
  720. if existing.Auth != incoming.Auth && incoming.Auth != "" {
  721. if incomingNewer || existing.Auth == "" {
  722. existing.Auth = incoming.Auth
  723. keepSecret("auth")
  724. }
  725. }
  726. if existing.Flow != incoming.Flow && incoming.Flow != "" {
  727. if incomingNewer || existing.Flow == "" {
  728. keep("flow", existing.Flow, incoming.Flow, incoming.Flow)
  729. existing.Flow = incoming.Flow
  730. }
  731. }
  732. if existing.Security != incoming.Security && incoming.Security != "" {
  733. if incomingNewer || existing.Security == "" {
  734. keep("security", existing.Security, incoming.Security, incoming.Security)
  735. existing.Security = incoming.Security
  736. }
  737. }
  738. if existing.SubID != incoming.SubID && incoming.SubID != "" {
  739. if incomingNewer || existing.SubID == "" {
  740. existing.SubID = incoming.SubID
  741. keepSecret("subId")
  742. }
  743. }
  744. if existing.TotalGB != incoming.TotalGB {
  745. picked := existing.TotalGB
  746. if existing.TotalGB == 0 || (incoming.TotalGB != 0 && incoming.TotalGB > existing.TotalGB) {
  747. picked = incoming.TotalGB
  748. }
  749. if picked != existing.TotalGB {
  750. keep("totalGB", existing.TotalGB, incoming.TotalGB, picked)
  751. existing.TotalGB = picked
  752. }
  753. }
  754. if existing.ExpiryTime != incoming.ExpiryTime {
  755. picked := existing.ExpiryTime
  756. if existing.ExpiryTime == 0 || (incoming.ExpiryTime != 0 && incoming.ExpiryTime > existing.ExpiryTime) {
  757. picked = incoming.ExpiryTime
  758. }
  759. if picked != existing.ExpiryTime {
  760. keep("expiryTime", existing.ExpiryTime, incoming.ExpiryTime, picked)
  761. existing.ExpiryTime = picked
  762. }
  763. }
  764. if existing.LimitIP != incoming.LimitIP && incoming.LimitIP != 0 {
  765. picked := existing.LimitIP
  766. if existing.LimitIP == 0 || incoming.LimitIP > existing.LimitIP {
  767. picked = incoming.LimitIP
  768. }
  769. if picked != existing.LimitIP {
  770. keep("limitIp", existing.LimitIP, incoming.LimitIP, picked)
  771. existing.LimitIP = picked
  772. }
  773. }
  774. if existing.TgID != incoming.TgID && incoming.TgID != 0 {
  775. if incomingNewer || existing.TgID == 0 {
  776. keep("tgId", existing.TgID, incoming.TgID, incoming.TgID)
  777. existing.TgID = incoming.TgID
  778. }
  779. }
  780. if existing.Reset != incoming.Reset && incoming.Reset != 0 {
  781. if incomingNewer || existing.Reset == 0 {
  782. keep("reset", existing.Reset, incoming.Reset, incoming.Reset)
  783. existing.Reset = incoming.Reset
  784. }
  785. }
  786. if existing.Reverse != incoming.Reverse && incoming.Reverse != "" {
  787. if incomingNewer || existing.Reverse == "" {
  788. keep("reverse", existing.Reverse, incoming.Reverse, incoming.Reverse)
  789. existing.Reverse = incoming.Reverse
  790. }
  791. }
  792. if existing.Comment != incoming.Comment && incoming.Comment != "" {
  793. if incomingNewer || existing.Comment == "" {
  794. keep("comment", existing.Comment, incoming.Comment, incoming.Comment)
  795. existing.Comment = incoming.Comment
  796. }
  797. }
  798. if existing.Group != incoming.Group && incoming.Group != "" {
  799. if incomingNewer || existing.Group == "" {
  800. keep("group", existing.Group, incoming.Group, incoming.Group)
  801. existing.Group = incoming.Group
  802. }
  803. }
  804. if existing.Enable != incoming.Enable {
  805. if incoming.Enable {
  806. if !existing.Enable {
  807. keep("enable", existing.Enable, incoming.Enable, true)
  808. existing.Enable = true
  809. }
  810. }
  811. }
  812. if incoming.CreatedAt != 0 && (existing.CreatedAt == 0 || incoming.CreatedAt < existing.CreatedAt) {
  813. existing.CreatedAt = incoming.CreatedAt
  814. }
  815. if incoming.UpdatedAt > existing.UpdatedAt {
  816. existing.UpdatedAt = incoming.UpdatedAt
  817. }
  818. return conflicts
  819. }