model.go 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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. // ApiTokenUnixMillisecondsThreshold separates legacy millisecond timestamps
  137. // from the seconds-based API token timestamp contract.
  138. const ApiTokenUnixMillisecondsThreshold int64 = 100_000_000_000
  139. type ApiToken struct {
  140. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  141. Name string `json:"name" gorm:"uniqueIndex;not null"`
  142. Token string `json:"token" gorm:"not null"` // SHA-256 hash; the plaintext is shown only once at creation
  143. Enabled bool `json:"enabled" gorm:"default:true"`
  144. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime"`
  145. }
  146. // MarshalJSON emits settings, streamSettings, and sniffing as nested JSON
  147. // objects rather than escaped strings, so API consumers don't need to JSON.parse
  148. // a string inside a string. Empty fields render as null; fields whose stored
  149. // text isn't valid JSON fall back to a JSON-encoded string so no data is lost.
  150. func (i Inbound) MarshalJSON() ([]byte, error) {
  151. type alias Inbound
  152. return json.Marshal(struct {
  153. alias
  154. Settings json.RawMessage `json:"settings"`
  155. StreamSettings json.RawMessage `json:"streamSettings"`
  156. Sniffing json.RawMessage `json:"sniffing"`
  157. }{
  158. alias: alias(i),
  159. Settings: jsonStringFieldToRaw(i.Settings),
  160. StreamSettings: jsonStringFieldToRaw(i.StreamSettings),
  161. Sniffing: jsonStringFieldToRaw(i.Sniffing),
  162. })
  163. }
  164. // UnmarshalJSON accepts settings, streamSettings, and sniffing as either a raw
  165. // JSON object/array (the modern shape MarshalJSON emits) or a JSON-encoded
  166. // string (the legacy shape). Either form is normalised back to the JSON-text
  167. // string the DB column stores.
  168. func (i *Inbound) UnmarshalJSON(data []byte) error {
  169. type alias Inbound
  170. aux := struct {
  171. *alias
  172. Settings json.RawMessage `json:"settings"`
  173. StreamSettings json.RawMessage `json:"streamSettings"`
  174. Sniffing json.RawMessage `json:"sniffing"`
  175. }{
  176. alias: (*alias)(i),
  177. }
  178. if err := json.Unmarshal(data, &aux); err != nil {
  179. return err
  180. }
  181. i.Settings = jsonStringFieldFromRaw(aux.Settings)
  182. i.StreamSettings = jsonStringFieldFromRaw(aux.StreamSettings)
  183. i.Sniffing = jsonStringFieldFromRaw(aux.Sniffing)
  184. return nil
  185. }
  186. func jsonStringFieldToRaw(s string) json.RawMessage {
  187. trimmed := strings.TrimSpace(s)
  188. if trimmed == "" {
  189. return json.RawMessage("null")
  190. }
  191. if json.Valid([]byte(trimmed)) {
  192. return json.RawMessage(trimmed)
  193. }
  194. b, _ := json.Marshal(s)
  195. return b
  196. }
  197. func jsonStringFieldFromRaw(r json.RawMessage) string {
  198. trimmed := bytes.TrimSpace(r)
  199. if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {
  200. return ""
  201. }
  202. if trimmed[0] == '"' {
  203. var s string
  204. if err := json.Unmarshal(trimmed, &s); err == nil {
  205. return s
  206. }
  207. }
  208. return string(trimmed)
  209. }
  210. // StripInboundXhttpClientFields removes xHTTP knobs that belong on the
  211. // client dialer and subscription share-link extras only. xray-core's XHTTP
  212. // inbound listener does not consume them; the panel still stores them on
  213. // the inbound row so buildXhttpExtra can push defaults to clients.
  214. func StripInboundXhttpClientFields(streamSettings string) (string, bool) {
  215. if streamSettings == "" {
  216. return streamSettings, false
  217. }
  218. var stream map[string]any
  219. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  220. return streamSettings, false
  221. }
  222. if stream["network"] != "xhttp" {
  223. return streamSettings, false
  224. }
  225. xhttp, ok := stream["xhttpSettings"].(map[string]any)
  226. if !ok || len(xhttp) == 0 {
  227. return streamSettings, false
  228. }
  229. clientOnly := []string{
  230. "xmux",
  231. "downloadSettings",
  232. "scMinPostsIntervalMs",
  233. "uplinkChunkSize",
  234. "noGRPCHeader",
  235. }
  236. changed := false
  237. for _, key := range clientOnly {
  238. if _, has := xhttp[key]; has {
  239. delete(xhttp, key)
  240. changed = true
  241. }
  242. }
  243. if !changed {
  244. return streamSettings, false
  245. }
  246. out, err := json.MarshalIndent(stream, "", " ")
  247. if err != nil {
  248. return streamSettings, false
  249. }
  250. return string(out), true
  251. }
  252. // GenXrayInboundConfig generates an Xray inbound configuration from the Inbound model.
  253. func (i *Inbound) GenXrayInboundConfig() *xray.InboundConfig {
  254. listen := i.Listen
  255. if listen == "" {
  256. listen = "0.0.0.0"
  257. }
  258. listen = fmt.Sprintf("\"%v\"", listen)
  259. protocol := string(i.Protocol)
  260. settings := i.Settings
  261. switch i.Protocol {
  262. case Shadowsocks:
  263. if healed, ok := HealShadowsocksClientMethods(settings); ok {
  264. settings = healed
  265. }
  266. case VMESS:
  267. if stripped, ok := StripVmessClientSecurity(settings); ok {
  268. settings = stripped
  269. }
  270. case VLESS:
  271. if stripped, ok := StripVlessInboundEncryption(settings); ok {
  272. settings = stripped
  273. }
  274. case WireGuard:
  275. if converted, ok := WireguardClientsToPeers(settings); ok {
  276. settings = converted
  277. }
  278. }
  279. streamSettings := i.StreamSettings
  280. if stripped, ok := StripInboundXhttpClientFields(streamSettings); ok {
  281. streamSettings = stripped
  282. }
  283. return &xray.InboundConfig{
  284. Listen: json_util.RawMessage(listen),
  285. Port: i.Port,
  286. Protocol: protocol,
  287. Settings: json_util.RawMessage(settings),
  288. StreamSettings: json_util.RawMessage(streamSettings),
  289. Tag: i.Tag,
  290. Sniffing: json_util.RawMessage(i.Sniffing),
  291. }
  292. }
  293. func StripVmessClientSecurity(settings string) (string, bool) {
  294. if settings == "" {
  295. return settings, false
  296. }
  297. var parsed map[string]any
  298. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  299. return settings, false
  300. }
  301. clients, ok := parsed["clients"].([]any)
  302. if !ok {
  303. return settings, false
  304. }
  305. changed := false
  306. for i := range clients {
  307. cm, ok := clients[i].(map[string]any)
  308. if !ok {
  309. continue
  310. }
  311. if _, has := cm["security"]; has {
  312. delete(cm, "security")
  313. clients[i] = cm
  314. changed = true
  315. }
  316. }
  317. if !changed {
  318. return settings, false
  319. }
  320. out, err := json.MarshalIndent(parsed, "", " ")
  321. if err != nil {
  322. return settings, false
  323. }
  324. return string(out), true
  325. }
  326. // WireguardPeerFromClient builds the xray wireguard inbound peer object for one
  327. // WireGuard client. It is the single definition of the peer shape, shared by the
  328. // full-config path (XrayService.GetXrayConfig) and the live AddInbound path
  329. // (WireguardClientsToPeers), so both emit identical peers. The client's
  330. // privateKey is intentionally omitted — it is the client's secret, not part of
  331. // the server-side peer.
  332. func WireguardPeerFromClient(c Client) map[string]any {
  333. peer := map[string]any{"email": c.Email, "level": 0}
  334. if c.PublicKey != "" {
  335. peer["publicKey"] = c.PublicKey
  336. }
  337. if len(c.AllowedIPs) > 0 {
  338. peer["allowedIPs"] = c.AllowedIPs
  339. }
  340. if c.PreSharedKey != "" {
  341. peer["preSharedKey"] = c.PreSharedKey
  342. }
  343. if c.KeepAlive > 0 {
  344. peer["keepAlive"] = c.KeepAlive
  345. }
  346. return peer
  347. }
  348. // WireguardClientsToPeers rewrites a WireGuard inbound's settings JSON from the
  349. // panel's client representation into the peers array xray-core's wireguard
  350. // inbound expects. The panel stores WireGuard clients under "clients" (the shape
  351. // every other protocol uses); xray is configured with "peers". GetXrayConfig
  352. // already does this conversion when it builds the full config, but the live
  353. // gRPC AddInbound paths (inbound create/edit and node reconcile) go through
  354. // GenXrayInboundConfig directly — without the conversion they re-add the
  355. // wireguard inbound with no peers, dropping every connected client until the
  356. // next full restart. Clients are the source of truth and are always rebuilt
  357. // into peers (matching GetXrayConfig), so the panel's empty "peers" placeholder
  358. // never blocks the conversion. Idempotent: converting removes "clients", so a
  359. // second call is a no-op, as is any inbound that carries no "clients".
  360. func WireguardClientsToPeers(settings string) (string, bool) {
  361. if settings == "" {
  362. return settings, false
  363. }
  364. var parsed map[string]any
  365. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  366. return settings, false
  367. }
  368. clients, ok := parsed["clients"].([]any)
  369. if !ok {
  370. return settings, false
  371. }
  372. peers := make([]any, 0, len(clients))
  373. for _, raw := range clients {
  374. cm, ok := raw.(map[string]any)
  375. if !ok {
  376. continue
  377. }
  378. if enable, ok := cm["enable"].(bool); ok && !enable {
  379. continue
  380. }
  381. encoded, err := json.Marshal(cm)
  382. if err != nil {
  383. continue
  384. }
  385. var c Client
  386. if err := json.Unmarshal(encoded, &c); err != nil {
  387. continue
  388. }
  389. peers = append(peers, WireguardPeerFromClient(c))
  390. }
  391. delete(parsed, "clients")
  392. parsed["peers"] = peers
  393. out, err := json.MarshalIndent(parsed, "", " ")
  394. if err != nil {
  395. return settings, false
  396. }
  397. return string(out), true
  398. }
  399. func StripVlessInboundEncryption(settings string) (string, bool) {
  400. if settings == "" {
  401. return settings, false
  402. }
  403. var parsed map[string]any
  404. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  405. return settings, false
  406. }
  407. if _, has := parsed["encryption"]; !has {
  408. return settings, false
  409. }
  410. delete(parsed, "encryption")
  411. out, err := json.MarshalIndent(parsed, "", " ")
  412. if err != nil {
  413. return settings, false
  414. }
  415. return string(out), true
  416. }
  417. // HealShadowsocksClientMethods normalises the per-client `method` field
  418. // on a shadowsocks inbound's settings JSON before it leaves for xray-core:
  419. // - Legacy ciphers (aes-*, chacha20-*): every client must carry a
  420. // per-user `method` matching the inbound's top-level method, otherwise
  421. // xray fails with "unsupported cipher method:".
  422. // - Shadowsocks 2022 (2022-blake3-*): xray's multi-user code rejects the
  423. // inbound with "users must have empty method" when a client carries
  424. // one — strip stale entries left over from a switch off a legacy
  425. // cipher.
  426. //
  427. // Returns the rewritten settings string and true when anything changed.
  428. func HealShadowsocksClientMethods(settings string) (string, bool) {
  429. if settings == "" {
  430. return settings, false
  431. }
  432. var parsed map[string]any
  433. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  434. return settings, false
  435. }
  436. method, _ := parsed["method"].(string)
  437. clients, ok := parsed["clients"].([]any)
  438. if !ok {
  439. return settings, false
  440. }
  441. is2022 := strings.HasPrefix(method, "2022-blake3-")
  442. changed := false
  443. for i := range clients {
  444. cm, ok := clients[i].(map[string]any)
  445. if !ok {
  446. continue
  447. }
  448. if is2022 {
  449. if _, hasKey := cm["method"]; hasKey {
  450. delete(cm, "method")
  451. clients[i] = cm
  452. changed = true
  453. }
  454. continue
  455. }
  456. if method == "" {
  457. continue
  458. }
  459. existing, _ := cm["method"].(string)
  460. if existing == method {
  461. continue
  462. }
  463. cm["method"] = method
  464. clients[i] = cm
  465. changed = true
  466. }
  467. if !changed {
  468. return settings, false
  469. }
  470. out, err := json.MarshalIndent(parsed, "", " ")
  471. if err != nil {
  472. return settings, false
  473. }
  474. return string(out), true
  475. }
  476. // GenerateFakeTLSSecret builds an MTProto FakeTLS secret for the given domain:
  477. // the "ee" FakeTLS marker, 16 random bytes, then the domain encoded as hex.
  478. // MTProto is multi-client, so this value belongs to one client: mtg's [secrets]
  479. // config and that client's tg:// link both read it per client.
  480. func GenerateFakeTLSSecret(domain string) string {
  481. return "ee" + mtprotoRandomMiddle() + hex.EncodeToString([]byte(domain))
  482. }
  483. func mtprotoRandomMiddle() string {
  484. buf := make([]byte, 16)
  485. if _, err := rand.Read(buf); err != nil {
  486. panic(fmt.Errorf("mtproto: crypto/rand read failed: %w", err))
  487. }
  488. return hex.EncodeToString(buf)
  489. }
  490. // mtprotoSecretMiddle returns the 16-byte random middle of an existing secret
  491. // when it is well-formed, otherwise a freshly generated one. Reusing the middle
  492. // keeps the secret stable when only the FakeTLS domain changes.
  493. func mtprotoSecretMiddle(secret string) string {
  494. s := secret
  495. if strings.HasPrefix(s, "ee") || strings.HasPrefix(s, "dd") {
  496. s = s[2:]
  497. }
  498. if len(s) >= 32 {
  499. mid := s[:32]
  500. if _, err := hex.DecodeString(mid); err == nil {
  501. return mid
  502. }
  503. }
  504. return mtprotoRandomMiddle()
  505. }
  506. // ValidMtprotoAdTag reports whether a Telegram advertising tag from
  507. // @MTProxybot is well-formed: exactly 16 bytes as 32 hex characters. mtg
  508. // refuses to start (or rejects a live update) on a malformed tag, so every
  509. // write path validates before the tag can reach a generated config.
  510. func ValidMtprotoAdTag(tag string) bool {
  511. if len(tag) != 32 {
  512. return false
  513. }
  514. _, err := hex.DecodeString(tag)
  515. return err == nil
  516. }
  517. // StripMtprotoInboundSecret removes the vestigial inbound-level `secret` from an
  518. // mtproto inbound's settings JSON. MTProto is multi-client: every secret lives on
  519. // a client, and mtg's [secrets] config plus every share link read only the
  520. // per-client secrets. A lingering inbound-level secret is dead data — it once
  521. // leaked into stale links that mtg rejected as "incorrect client random". Returns
  522. // the rewritten settings and true when a `secret` key was removed.
  523. func StripMtprotoInboundSecret(settings string) (string, bool) {
  524. if settings == "" {
  525. return settings, false
  526. }
  527. var parsed map[string]any
  528. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  529. return settings, false
  530. }
  531. if _, ok := parsed["secret"]; !ok {
  532. return settings, false
  533. }
  534. delete(parsed, "secret")
  535. out, err := json.MarshalIndent(parsed, "", " ")
  536. if err != nil {
  537. return settings, false
  538. }
  539. return string(out), true
  540. }
  541. // StripMtprotoInboundAdTag drops the dead inbound-level `adTag` — tags live on clients.
  542. func StripMtprotoInboundAdTag(settings string) (string, bool) {
  543. if settings == "" {
  544. return settings, false
  545. }
  546. var parsed map[string]any
  547. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  548. return settings, false
  549. }
  550. if _, ok := parsed["adTag"]; !ok {
  551. return settings, false
  552. }
  553. delete(parsed, "adTag")
  554. out, err := json.MarshalIndent(parsed, "", " ")
  555. if err != nil {
  556. return settings, false
  557. }
  558. return string(out), true
  559. }
  560. // mtprotoSecretDomain extracts the FakeTLS domain embedded in the tail of a
  561. // secret, returning an empty string when the secret is malformed. Each mtproto
  562. // client carries its own domain inside its secret, so healing preserves it
  563. // instead of forcing every client onto the inbound-level default.
  564. func mtprotoSecretDomain(secret string) string {
  565. s := secret
  566. if strings.HasPrefix(s, "ee") || strings.HasPrefix(s, "dd") {
  567. s = s[2:]
  568. }
  569. if len(s) <= 32 {
  570. return ""
  571. }
  572. decoded, err := hex.DecodeString(s[32:])
  573. if err != nil || len(decoded) == 0 {
  574. return ""
  575. }
  576. return string(decoded)
  577. }
  578. // HealMtprotoClientSecrets normalises every client's FakeTLS secret in an
  579. // mtproto inbound's settings JSON: each secret is rebuilt so it stays a valid
  580. // FakeTLS value, keeping the client's own embedded domain when present and
  581. // falling back to the inbound-level fakeTlsDomain otherwise. Returns the
  582. // rewritten settings and true when anything changed.
  583. func HealMtprotoClientSecrets(settings string) (string, bool) {
  584. if settings == "" {
  585. return settings, false
  586. }
  587. var parsed map[string]any
  588. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  589. return settings, false
  590. }
  591. clients, ok := parsed["clients"].([]any)
  592. if !ok || len(clients) == 0 {
  593. return settings, false
  594. }
  595. defaultDomain, _ := parsed["fakeTlsDomain"].(string)
  596. defaultDomain = strings.TrimSpace(defaultDomain)
  597. changed := false
  598. for _, raw := range clients {
  599. client, ok := raw.(map[string]any)
  600. if !ok {
  601. continue
  602. }
  603. secret, _ := client["secret"].(string)
  604. domain := mtprotoSecretDomain(secret)
  605. if domain == "" {
  606. domain = defaultDomain
  607. }
  608. if domain == "" {
  609. continue
  610. }
  611. expected := "ee" + mtprotoSecretMiddle(secret) + hex.EncodeToString([]byte(domain))
  612. if secret != expected {
  613. client["secret"] = expected
  614. changed = true
  615. }
  616. }
  617. if !changed {
  618. return settings, false
  619. }
  620. out, err := json.MarshalIndent(parsed, "", " ")
  621. if err != nil {
  622. return settings, false
  623. }
  624. return string(out), true
  625. }
  626. // Setting stores key-value configuration settings for the 3x-ui panel.
  627. type Setting struct {
  628. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
  629. Key string `json:"key" form:"key" gorm:"index:idx_settings_key"`
  630. Value string `json:"value" form:"value"`
  631. }
  632. // Node represents a remote 3x-ui panel registered with the central panel.
  633. // The central panel polls each node's existing /panel/api/server/status
  634. // endpoint over HTTP using the per-node ApiToken to populate the runtime
  635. // status fields below.
  636. type Node struct {
  637. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement" example:"1"`
  638. Name string `json:"name" form:"name" gorm:"uniqueIndex" validate:"required" example:"de-fra-1"`
  639. Remark string `json:"remark" form:"remark"`
  640. Scheme string `json:"scheme" form:"scheme" validate:"omitempty,oneof=http https" example:"https"`
  641. Address string `json:"address" form:"address" validate:"required" example:"node1.example.com"`
  642. Port int `json:"port" form:"port" validate:"gte=1,lte=65535" example:"2053"`
  643. BasePath string `json:"basePath" form:"basePath" example:"/"`
  644. ApiToken string `json:"apiToken" form:"apiToken" validate:"required_unless=TlsVerifyMode mtls" example:"abcdef0123456789"`
  645. Enable bool `json:"enable" form:"enable" gorm:"default:true" example:"true"`
  646. AllowPrivateAddress bool `json:"allowPrivateAddress" form:"allowPrivateAddress" gorm:"default:false"`
  647. TlsVerifyMode string `json:"tlsVerifyMode" form:"tlsVerifyMode" gorm:"column:tls_verify_mode;default:verify" validate:"omitempty,oneof=verify skip pin mtls"`
  648. PinnedCertSha256 string `json:"pinnedCertSha256" form:"pinnedCertSha256" gorm:"column:pinned_cert_sha256"`
  649. InboundSyncMode string `json:"inboundSyncMode" form:"inboundSyncMode" gorm:"column:inbound_sync_mode;default:all" validate:"omitempty,oneof=all selected"`
  650. InboundTags []string `json:"inboundTags" form:"inboundTags" gorm:"serializer:json;column:inbound_tags"`
  651. OutboundTag string `json:"outboundTag" form:"outboundTag" gorm:"column:outbound_tag"`
  652. // Guid is the remote panel's stable self-identifier (its panelGuid),
  653. // learned from each heartbeat. It is the globally stable node identity used
  654. // to attribute online clients/inbounds to the physical node across a chain
  655. // of nodes (#4983); panel-local autoincrement ids don't survive a hop.
  656. // Observed-state only — never user-edited.
  657. Guid string `json:"guid" gorm:"column:guid;index"`
  658. // Heartbeat-updated fields. UpdatedAt advances on every probe even when
  659. // the row is otherwise unchanged so the UI's "last seen" tooltip is
  660. // truthful without us having to read LastHeartbeat separately.
  661. Status string `json:"status" gorm:"default:unknown" example:"online"` // online|offline|unknown
  662. LastHeartbeat int64 `json:"lastHeartbeat" example:"1700000000"` // unix seconds, 0 = never
  663. LatencyMs int `json:"latencyMs" example:"42"`
  664. XrayVersion string `json:"xrayVersion" example:"25.10.31"`
  665. PanelVersion string `json:"panelVersion" gorm:"column:panel_version" example:"v3.x.x"`
  666. CpuPct float64 `json:"cpuPct" example:"23.5"`
  667. MemPct float64 `json:"memPct" example:"45.1"`
  668. UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
  669. NetUp uint64 `json:"netUp" gorm:"column:net_up" example:"1048576"`
  670. NetDown uint64 `json:"netDown" gorm:"column:net_down" example:"2097152"`
  671. LastError string `json:"lastError"`
  672. // XrayState and XrayError are captured from the remote node's /panel/api/server/status
  673. // during heartbeats. They let the central panel distinguish "panel API reachable"
  674. // (status=online) from "Xray core itself has failed on the node" for monitoring.
  675. XrayState string `json:"xrayState" gorm:"column:xray_state"`
  676. XrayError string `json:"xrayError" gorm:"column:xray_error"`
  677. ConfigDirty bool `json:"configDirty" gorm:"default:false"`
  678. ConfigDirtyAt int64 `json:"configDirtyAt"`
  679. InboundCount int `json:"inboundCount" gorm:"-" example:"5"`
  680. ClientCount int `json:"clientCount" gorm:"-" example:"27"`
  681. OnlineCount int `json:"onlineCount" gorm:"-" example:"3"`
  682. ActiveCount int `json:"activeCount" gorm:"-" example:"23"`
  683. DisabledCount int `json:"disabledCount" gorm:"-" example:"3"`
  684. DepletedCount int `json:"depletedCount" gorm:"-" example:"1"`
  685. // ParentGuid + Transitive are set only when a node is surfaced as part of a
  686. // node tree (#4983): direct nodes carry the master panel's own GUID, a
  687. // transitive sub-node carries its parent node's GUID. Transitive nodes are
  688. // read-only projections (Id == 0, not persisted) — never edited or deployed.
  689. ParentGuid string `json:"parentGuid,omitempty" gorm:"-"`
  690. Transitive bool `json:"transitive,omitempty" gorm:"-"`
  691. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli" example:"1700000000"`
  692. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli" example:"1700000000"`
  693. }
  694. // NodeSummary is the read-only identity of a node as published one hop up: the
  695. // view a panel exposes about the nodes it directly manages, so a master can
  696. // surface transitive sub-nodes in a chained topology (#4983). Counts are
  697. // computed by the consuming master from its own per-GUID data, never trusted
  698. // from the child, so this carries identity/health only.
  699. type NodeSummary struct {
  700. Guid string `json:"guid"`
  701. ParentGuid string `json:"parentGuid"`
  702. Name string `json:"name"`
  703. Address string `json:"address"`
  704. Scheme string `json:"scheme"`
  705. Port int `json:"port"`
  706. Status string `json:"status"`
  707. LastHeartbeat int64 `json:"lastHeartbeat"`
  708. LatencyMs int `json:"latencyMs"`
  709. PanelVersion string `json:"panelVersion"`
  710. XrayVersion string `json:"xrayVersion"`
  711. // XrayState/XrayError forwarded so masters can surface xray failure on transitive sub-nodes too.
  712. XrayState string `json:"xrayState"`
  713. XrayError string `json:"xrayError,omitempty"`
  714. }
  715. type ClientReverse struct {
  716. Tag string `json:"tag"`
  717. }
  718. // Client represents a client configuration for Xray inbounds with traffic limits and settings.
  719. type Client struct {
  720. ID string `json:"id,omitempty"` // Unique client identifier
  721. Security string `json:"security"` // Security method (e.g., "auto", "aes-128-gcm")
  722. Password string `json:"password,omitempty"` // Client password
  723. Flow string `json:"flow,omitempty"` // Flow control (XTLS)
  724. Reverse *ClientReverse `json:"reverse,omitempty"` // VLESS simple reverse proxy settings
  725. Auth string `json:"auth,omitempty"` // Auth password (Hysteria)
  726. PrivateKey string `json:"privateKey,omitempty"`
  727. PublicKey string `json:"publicKey,omitempty"`
  728. AllowedIPs []string `json:"allowedIPs,omitempty"`
  729. PreSharedKey string `json:"preSharedKey,omitempty"`
  730. KeepAlive int `json:"keepAlive,omitempty"`
  731. Secret string `json:"secret,omitempty" example:"ee1234567890abcdef1234567890abcd7777772e636c6f7564666c6172652e636f6d"`
  732. AdTag string `json:"adTag,omitempty" example:"0123456789abcdef0123456789abcdef"`
  733. Email string `json:"email"` // Client email identifier
  734. LimitIP int `json:"limitIp"` // IP limit for this client
  735. TotalGB int64 `json:"totalGB" form:"totalGB"` // Total traffic limit in GB
  736. ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` // Expiration timestamp
  737. Enable bool `json:"enable" form:"enable"` // Whether the client is enabled
  738. TgID int64 `json:"tgId" form:"tgId"` // Telegram user ID for notifications
  739. SubID string `json:"subId" form:"subId"` // Subscription identifier
  740. Group string `json:"group,omitempty" form:"group"` // Logical grouping label
  741. Comment string `json:"comment" form:"comment"` // Client comment
  742. Reset int `json:"reset" form:"reset"` // Reset period in days
  743. CreatedAt int64 `json:"created_at,omitempty"` // Creation timestamp
  744. UpdatedAt int64 `json:"updated_at,omitempty"` // Last update timestamp
  745. }
  746. type ClientRecord struct {
  747. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  748. Email string `json:"email" gorm:"uniqueIndex;not null"`
  749. SubID string `json:"subId" gorm:"index;column:sub_id"`
  750. UUID string `json:"uuid" gorm:"column:uuid"`
  751. Password string `json:"password"`
  752. Auth string `json:"auth"`
  753. Flow string `json:"flow"`
  754. Security string `json:"security"`
  755. Reverse string `json:"reverse" gorm:"column:reverse"`
  756. PrivateKey string `json:"privateKey" gorm:"column:wg_private_key"`
  757. PublicKey string `json:"publicKey" gorm:"column:wg_public_key"`
  758. AllowedIPs string `json:"allowedIPs" gorm:"column:wg_allowed_ips"`
  759. PreSharedKey string `json:"preSharedKey" gorm:"column:wg_pre_shared_key"`
  760. KeepAlive int `json:"keepAlive" gorm:"column:wg_keep_alive;default:0"`
  761. Secret string `json:"secret" gorm:"column:secret"`
  762. AdTag string `json:"adTag" gorm:"column:ad_tag;default:''"`
  763. LimitIP int `json:"limitIp" gorm:"column:limit_ip"`
  764. TotalGB int64 `json:"totalGB" gorm:"column:total_gb"`
  765. ExpiryTime int64 `json:"expiryTime" gorm:"column:expiry_time"`
  766. Enable bool `json:"enable" gorm:"default:true"`
  767. TgID int64 `json:"tgId" gorm:"column:tg_id"`
  768. Group string `json:"group" gorm:"column:group_name;default:'';index:idx_client_record_group"`
  769. Comment string `json:"comment"`
  770. Reset int `json:"reset" gorm:"default:0"`
  771. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  772. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  773. }
  774. func (ClientRecord) TableName() string { return "clients" }
  775. type ClientGroup struct {
  776. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  777. Name string `json:"name" gorm:"uniqueIndex;not null"`
  778. ResetUp int64 `json:"resetUp" gorm:"column:reset_up;default:0"`
  779. ResetDown int64 `json:"resetDown" gorm:"column:reset_down;default:0"`
  780. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  781. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  782. }
  783. func (ClientGroup) TableName() string { return "client_groups" }
  784. // MarshalJSON emits the reverse column as a nested JSON object rather than an
  785. // escaped JSON-text string, matching the same convention Inbound uses for its
  786. // JSON-text columns. Empty storage renders as null.
  787. func (r ClientRecord) MarshalJSON() ([]byte, error) {
  788. type alias ClientRecord
  789. return json.Marshal(struct {
  790. alias
  791. Reverse json.RawMessage `json:"reverse"`
  792. }{
  793. alias: alias(r),
  794. Reverse: jsonStringFieldToRaw(r.Reverse),
  795. })
  796. }
  797. // UnmarshalJSON accepts reverse as either a JSON object (modern shape) or a
  798. // JSON-encoded string (legacy shape).
  799. func (r *ClientRecord) UnmarshalJSON(data []byte) error {
  800. type alias ClientRecord
  801. aux := struct {
  802. *alias
  803. Reverse json.RawMessage `json:"reverse"`
  804. }{
  805. alias: (*alias)(r),
  806. }
  807. if err := json.Unmarshal(data, &aux); err != nil {
  808. return err
  809. }
  810. r.Reverse = jsonStringFieldFromRaw(aux.Reverse)
  811. return nil
  812. }
  813. type ClientInbound struct {
  814. ClientId int `json:"clientId" gorm:"primaryKey;column:client_id;index"`
  815. InboundId int `json:"inboundId" gorm:"primaryKey;column:inbound_id;index"`
  816. FlowOverride string `json:"flowOverride" gorm:"column:flow_override"`
  817. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  818. }
  819. func (ClientInbound) TableName() string { return "client_inbounds" }
  820. // ClientExternalLink is a per-client entry surfaced in the client's
  821. // subscription. Two kinds:
  822. // - "link": a single third-party share link (vless://, vmess://, trojan://,
  823. // ss://, hysteria2://, wireguard://). Emitted verbatim in raw subs; parsed
  824. // into an outbound/proxy for JSON and Clash.
  825. // - "subscription": a remote subscription URL. The panel fetches it (cached),
  826. // decodes its links, and merges them into the client's subscription.
  827. type ClientExternalLink struct {
  828. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  829. ClientId int `json:"clientId" gorm:"index;column:client_id"`
  830. Kind string `json:"kind" gorm:"column:kind"`
  831. Value string `json:"value" gorm:"column:value"`
  832. Remark string `json:"remark" gorm:"column:remark"`
  833. SortIndex int `json:"sortIndex" gorm:"column:sort_index"`
  834. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  835. }
  836. func (ClientExternalLink) TableName() string { return "client_external_links" }
  837. // External link kinds.
  838. const (
  839. ExternalLinkKindLink = "link"
  840. ExternalLinkKindSubscription = "subscription"
  841. )
  842. type InboundFallback struct {
  843. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  844. MasterId int `json:"masterId" gorm:"index;not null;column:master_id"`
  845. ChildId int `json:"childId" gorm:"index;not null;column:child_id"`
  846. Name string `json:"name"`
  847. Alpn string `json:"alpn"`
  848. Path string `json:"path"`
  849. Dest string `json:"dest"`
  850. Xver int `json:"xver"`
  851. SortOrder int `json:"sortOrder" gorm:"default:0;column:sort_order"`
  852. }
  853. func (InboundFallback) TableName() string { return "inbound_fallbacks" }
  854. type Host struct {
  855. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement" example:"1"`
  856. GroupId string `json:"groupId" form:"groupId" gorm:"column:group_id;index"`
  857. InboundId int `json:"inboundId" form:"inboundId" gorm:"index;not null;column:inbound_id" validate:"required" example:"1"`
  858. SortOrder int `json:"sortOrder" form:"sortOrder" gorm:"default:0;column:sort_order"`
  859. Remark string `json:"remark" form:"remark" validate:"required,max=256" example:"cdn-front"`
  860. ServerDescription string `json:"serverDescription" form:"serverDescription" gorm:"column:server_description" validate:"omitempty,max=64"`
  861. IsDisabled bool `json:"isDisabled" form:"isDisabled" gorm:"default:false;column:is_disabled"`
  862. IsHidden bool `json:"isHidden" form:"isHidden" gorm:"default:false;column:is_hidden"`
  863. Tags []string `json:"tags" form:"tags" gorm:"serializer:json"`
  864. Address string `json:"address" form:"address" example:"cdn.example.com"`
  865. Port int `json:"port" form:"port" gorm:"default:0" validate:"gte=0,lte=65535" example:"8443"`
  866. Security string `json:"security" form:"security" gorm:"default:same" validate:"omitempty,oneof=same tls none reality" example:"same"`
  867. Sni string `json:"sni" form:"sni"`
  868. HostHeader string `json:"hostHeader" form:"hostHeader" gorm:"column:host_header"`
  869. Path string `json:"path" form:"path"`
  870. Alpn []string `json:"alpn" form:"alpn" gorm:"serializer:json"`
  871. Fingerprint string `json:"fingerprint" form:"fingerprint"`
  872. OverrideSniFromAddress bool `json:"overrideSniFromAddress" form:"overrideSniFromAddress" gorm:"column:override_sni_from_address"`
  873. KeepSniBlank bool `json:"keepSniBlank" form:"keepSniBlank" gorm:"column:keep_sni_blank"`
  874. PinnedPeerCertSha256 []string `json:"pinnedPeerCertSha256" form:"pinnedPeerCertSha256" gorm:"serializer:json;column:pinned_peer_cert_sha256"`
  875. VerifyPeerCertByName string `json:"verifyPeerCertByName" form:"verifyPeerCertByName" gorm:"column:verify_peer_cert_by_name"`
  876. AllowInsecure bool `json:"allowInsecure" form:"allowInsecure" gorm:"column:allow_insecure"`
  877. EchConfigList string `json:"echConfigList" form:"echConfigList" gorm:"column:ech_config_list"`
  878. MuxParams string `json:"muxParams" form:"muxParams" gorm:"type:text;column:mux_params"`
  879. SockoptParams string `json:"sockoptParams" form:"sockoptParams" gorm:"type:text;column:sockopt_params"`
  880. // FinalMask is a JSON object of xray finalmask masks (tcp/udp/quicParams),
  881. // merged into this host's JSON-subscription stream. Empty = no override.
  882. FinalMask string `json:"finalMask" form:"finalMask" gorm:"type:text;column:final_mask"`
  883. // Single VLESS route value (0-65535) baked into the subscription UUID's 3rd
  884. // group (bytes 6-7), which xray reads via net.PortFromBytes(id[6:8]). Empty = none.
  885. VlessRoute string `json:"vlessRoute" form:"vlessRoute" gorm:"column:vless_route" example:"443"`
  886. ExcludeFromSubTypes []string `json:"excludeFromSubTypes" form:"excludeFromSubTypes" gorm:"serializer:json;column:exclude_from_sub_types"`
  887. MihomoIpVersion string `json:"mihomoIpVersion" form:"mihomoIpVersion" gorm:"column:mihomo_ip_version" validate:"omitempty,oneof=dual ipv4 ipv6 ipv4-prefer ipv6-prefer"`
  888. MihomoX25519 bool `json:"mihomoX25519" form:"mihomoX25519" gorm:"column:mihomo_x25519"`
  889. ShuffleHost bool `json:"shuffleHost" form:"shuffleHost" gorm:"column:shuffle_host"`
  890. NodeGuids []string `json:"nodeGuids,omitempty" form:"nodeGuids" gorm:"serializer:json;column:node_guids"`
  891. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  892. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  893. }
  894. func (Host) TableName() string { return "hosts" }
  895. func (c *Client) ToRecord() *ClientRecord {
  896. rec := &ClientRecord{
  897. Email: c.Email,
  898. SubID: c.SubID,
  899. UUID: c.ID,
  900. Password: c.Password,
  901. Auth: c.Auth,
  902. Flow: c.Flow,
  903. Security: c.Security,
  904. LimitIP: c.LimitIP,
  905. TotalGB: c.TotalGB,
  906. ExpiryTime: c.ExpiryTime,
  907. Enable: c.Enable,
  908. TgID: c.TgID,
  909. Group: c.Group,
  910. Comment: c.Comment,
  911. Reset: c.Reset,
  912. CreatedAt: c.CreatedAt,
  913. UpdatedAt: c.UpdatedAt,
  914. PrivateKey: c.PrivateKey,
  915. PublicKey: c.PublicKey,
  916. AllowedIPs: strings.Join(c.AllowedIPs, ","),
  917. PreSharedKey: c.PreSharedKey,
  918. KeepAlive: c.KeepAlive,
  919. Secret: c.Secret,
  920. AdTag: c.AdTag,
  921. }
  922. if c.Reverse != nil {
  923. if b, err := json.Marshal(c.Reverse); err == nil {
  924. rec.Reverse = string(b)
  925. }
  926. }
  927. return rec
  928. }
  929. func splitWireguardAllowedIPs(csv string) []string {
  930. if csv == "" {
  931. return nil
  932. }
  933. parts := strings.Split(csv, ",")
  934. out := make([]string, 0, len(parts))
  935. for _, p := range parts {
  936. if trimmed := strings.TrimSpace(p); trimmed != "" {
  937. out = append(out, trimmed)
  938. }
  939. }
  940. if len(out) == 0 {
  941. return nil
  942. }
  943. return out
  944. }
  945. func (r *ClientRecord) ToClient() *Client {
  946. c := &Client{
  947. ID: r.UUID,
  948. Email: r.Email,
  949. SubID: r.SubID,
  950. Password: r.Password,
  951. Auth: r.Auth,
  952. Flow: r.Flow,
  953. Security: r.Security,
  954. LimitIP: r.LimitIP,
  955. TotalGB: r.TotalGB,
  956. ExpiryTime: r.ExpiryTime,
  957. Enable: r.Enable,
  958. TgID: r.TgID,
  959. Group: r.Group,
  960. Comment: r.Comment,
  961. Reset: r.Reset,
  962. CreatedAt: r.CreatedAt,
  963. UpdatedAt: r.UpdatedAt,
  964. PrivateKey: r.PrivateKey,
  965. PublicKey: r.PublicKey,
  966. AllowedIPs: splitWireguardAllowedIPs(r.AllowedIPs),
  967. PreSharedKey: r.PreSharedKey,
  968. KeepAlive: r.KeepAlive,
  969. Secret: r.Secret,
  970. AdTag: r.AdTag,
  971. }
  972. if r.Reverse != "" {
  973. var rev ClientReverse
  974. if err := json.Unmarshal([]byte(r.Reverse), &rev); err == nil {
  975. c.Reverse = &rev
  976. }
  977. }
  978. return c
  979. }
  980. type ClientMergeConflict struct {
  981. Field string
  982. Old any
  983. New any
  984. Kept any
  985. }
  986. type OutboundSubscription struct {
  987. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
  988. Remark string `json:"remark" form:"remark"`
  989. Url string `json:"url" form:"url"`
  990. Enabled bool `json:"enabled" form:"enabled" gorm:"default:true"`
  991. AllowPrivate bool `json:"allowPrivate" form:"allowPrivate" gorm:"default:false"`
  992. TagPrefix string `json:"tagPrefix" form:"tagPrefix"`
  993. UpdateInterval int `json:"updateInterval" form:"updateInterval" gorm:"default:600"` // seconds between refreshes
  994. Priority int `json:"priority" form:"priority" gorm:"default:0"` // order among subscriptions in the merged outbounds (lower = earlier)
  995. Prepend bool `json:"prepend" form:"prepend" gorm:"default:false"` // place this subscription's outbounds before the manual template outbounds
  996. LastUpdated int64 `json:"lastUpdated" form:"lastUpdated"`
  997. LastError string `json:"lastError" form:"lastError"`
  998. LastFetchedOutbounds string `json:"lastFetchedOutbounds" form:"lastFetchedOutbounds" gorm:"type:text"`
  999. LinkIdentities string `json:"-" gorm:"type:text;column:link_identities"`
  1000. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  1001. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  1002. OutboundCount int `json:"outboundCount" gorm:"-"`
  1003. }
  1004. func MergeClientRecord(existing *ClientRecord, incoming *ClientRecord) []ClientMergeConflict {
  1005. var conflicts []ClientMergeConflict
  1006. keep := func(field string, oldV, newV, kept any) {
  1007. conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: oldV, New: newV, Kept: kept})
  1008. }
  1009. const redacted = "<redacted>"
  1010. keepSecret := func(field string) {
  1011. conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: redacted, New: redacted, Kept: redacted})
  1012. }
  1013. incomingNewer := incoming.UpdatedAt > existing.UpdatedAt ||
  1014. (incoming.UpdatedAt == existing.UpdatedAt && incoming.CreatedAt > existing.CreatedAt)
  1015. if existing.UUID != incoming.UUID && incoming.UUID != "" {
  1016. if incomingNewer || existing.UUID == "" {
  1017. existing.UUID = incoming.UUID
  1018. }
  1019. keepSecret("uuid")
  1020. }
  1021. if existing.Password != incoming.Password && incoming.Password != "" {
  1022. if incomingNewer || existing.Password == "" {
  1023. existing.Password = incoming.Password
  1024. keepSecret("password")
  1025. }
  1026. }
  1027. if existing.Auth != incoming.Auth && incoming.Auth != "" {
  1028. if incomingNewer || existing.Auth == "" {
  1029. existing.Auth = incoming.Auth
  1030. keepSecret("auth")
  1031. }
  1032. }
  1033. if existing.Flow != incoming.Flow && incoming.Flow != "" {
  1034. if incomingNewer || existing.Flow == "" {
  1035. keep("flow", existing.Flow, incoming.Flow, incoming.Flow)
  1036. existing.Flow = incoming.Flow
  1037. }
  1038. }
  1039. if existing.Security != incoming.Security && incoming.Security != "" {
  1040. if incomingNewer || existing.Security == "" {
  1041. keep("security", existing.Security, incoming.Security, incoming.Security)
  1042. existing.Security = incoming.Security
  1043. }
  1044. }
  1045. if existing.SubID != incoming.SubID && incoming.SubID != "" {
  1046. if incomingNewer || existing.SubID == "" {
  1047. existing.SubID = incoming.SubID
  1048. keepSecret("subId")
  1049. }
  1050. }
  1051. if existing.TotalGB != incoming.TotalGB {
  1052. picked := existing.TotalGB
  1053. if existing.TotalGB == 0 || (incoming.TotalGB != 0 && incoming.TotalGB > existing.TotalGB) {
  1054. picked = incoming.TotalGB
  1055. }
  1056. if picked != existing.TotalGB {
  1057. keep("totalGB", existing.TotalGB, incoming.TotalGB, picked)
  1058. existing.TotalGB = picked
  1059. }
  1060. }
  1061. if existing.ExpiryTime != incoming.ExpiryTime {
  1062. picked := existing.ExpiryTime
  1063. if existing.ExpiryTime == 0 || (incoming.ExpiryTime != 0 && incoming.ExpiryTime > existing.ExpiryTime) {
  1064. picked = incoming.ExpiryTime
  1065. }
  1066. if picked != existing.ExpiryTime {
  1067. keep("expiryTime", existing.ExpiryTime, incoming.ExpiryTime, picked)
  1068. existing.ExpiryTime = picked
  1069. }
  1070. }
  1071. if existing.LimitIP != incoming.LimitIP && incoming.LimitIP != 0 {
  1072. picked := existing.LimitIP
  1073. if existing.LimitIP == 0 || incoming.LimitIP > existing.LimitIP {
  1074. picked = incoming.LimitIP
  1075. }
  1076. if picked != existing.LimitIP {
  1077. keep("limitIp", existing.LimitIP, incoming.LimitIP, picked)
  1078. existing.LimitIP = picked
  1079. }
  1080. }
  1081. if existing.TgID != incoming.TgID && incoming.TgID != 0 {
  1082. if incomingNewer || existing.TgID == 0 {
  1083. keep("tgId", existing.TgID, incoming.TgID, incoming.TgID)
  1084. existing.TgID = incoming.TgID
  1085. }
  1086. }
  1087. if existing.Reset != incoming.Reset && incoming.Reset != 0 {
  1088. if incomingNewer || existing.Reset == 0 {
  1089. keep("reset", existing.Reset, incoming.Reset, incoming.Reset)
  1090. existing.Reset = incoming.Reset
  1091. }
  1092. }
  1093. if existing.Reverse != incoming.Reverse && incoming.Reverse != "" {
  1094. if incomingNewer || existing.Reverse == "" {
  1095. keep("reverse", existing.Reverse, incoming.Reverse, incoming.Reverse)
  1096. existing.Reverse = incoming.Reverse
  1097. }
  1098. }
  1099. if existing.PrivateKey != incoming.PrivateKey && incoming.PrivateKey != "" {
  1100. if incomingNewer || existing.PrivateKey == "" {
  1101. existing.PrivateKey = incoming.PrivateKey
  1102. keepSecret("privateKey")
  1103. }
  1104. }
  1105. if existing.PublicKey != incoming.PublicKey && incoming.PublicKey != "" {
  1106. if incomingNewer || existing.PublicKey == "" {
  1107. existing.PublicKey = incoming.PublicKey
  1108. keepSecret("publicKey")
  1109. }
  1110. }
  1111. if existing.PreSharedKey != incoming.PreSharedKey && incoming.PreSharedKey != "" {
  1112. if incomingNewer || existing.PreSharedKey == "" {
  1113. existing.PreSharedKey = incoming.PreSharedKey
  1114. keepSecret("preSharedKey")
  1115. }
  1116. }
  1117. if existing.Secret != incoming.Secret && incoming.Secret != "" {
  1118. if incomingNewer || existing.Secret == "" {
  1119. existing.Secret = incoming.Secret
  1120. keepSecret("secret")
  1121. }
  1122. }
  1123. if existing.AllowedIPs != incoming.AllowedIPs && incoming.AllowedIPs != "" {
  1124. if incomingNewer || existing.AllowedIPs == "" {
  1125. keep("allowedIPs", existing.AllowedIPs, incoming.AllowedIPs, incoming.AllowedIPs)
  1126. existing.AllowedIPs = incoming.AllowedIPs
  1127. }
  1128. }
  1129. if existing.KeepAlive != incoming.KeepAlive && incoming.KeepAlive != 0 {
  1130. if incomingNewer || existing.KeepAlive == 0 {
  1131. keep("keepAlive", existing.KeepAlive, incoming.KeepAlive, incoming.KeepAlive)
  1132. existing.KeepAlive = incoming.KeepAlive
  1133. }
  1134. }
  1135. if existing.Comment != incoming.Comment && incoming.Comment != "" {
  1136. if incomingNewer || existing.Comment == "" {
  1137. keep("comment", existing.Comment, incoming.Comment, incoming.Comment)
  1138. existing.Comment = incoming.Comment
  1139. }
  1140. }
  1141. if existing.Group != incoming.Group && incoming.Group != "" {
  1142. if incomingNewer || existing.Group == "" {
  1143. keep("group", existing.Group, incoming.Group, incoming.Group)
  1144. existing.Group = incoming.Group
  1145. }
  1146. }
  1147. if existing.Enable != incoming.Enable {
  1148. if incoming.Enable {
  1149. if !existing.Enable {
  1150. keep("enable", existing.Enable, incoming.Enable, true)
  1151. existing.Enable = true
  1152. }
  1153. }
  1154. }
  1155. if incoming.CreatedAt != 0 && (existing.CreatedAt == 0 || incoming.CreatedAt < existing.CreatedAt) {
  1156. existing.CreatedAt = incoming.CreatedAt
  1157. }
  1158. if incoming.UpdatedAt > existing.UpdatedAt {
  1159. existing.UpdatedAt = incoming.UpdatedAt
  1160. }
  1161. return conflicts
  1162. }