1
0

model.go 61 KB

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