1
0

model.go 34 KB

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