model.go 63 KB

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