1
0

model.go 53 KB

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