model.go 62 KB

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