1
0

model.go 29 KB

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