1
0

model.go 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  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 is the clean sync that imported the node's inbounds; a
  776. // save that grows the selection zeroes it so reconcile waits before sweeping.
  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 disables monthly renewal
  852. ResetWeekday int `json:"resetWeekday" form:"resetWeekday"` // Calendar weekday 1-7 (Mon-Sun), 0 disables weekly renewal
  853. ResetMax int `json:"resetMax" form:"resetMax"` // Max auto-renew count, 0 = unlimited
  854. // Per-client traffic reset cycle, independent of the inbound's own (#5497).
  855. TrafficReset string `json:"trafficReset,omitempty" form:"trafficReset" validate:"omitempty,oneof=never hourly daily weekly monthly"`
  856. TrafficResetDay int `json:"trafficResetDay,omitempty" form:"trafficResetDay" validate:"omitempty,gte=1,lte=31"`
  857. CreatedAt int64 `json:"created_at,omitempty"` // Creation timestamp
  858. UpdatedAt int64 `json:"updated_at,omitempty"` // Last update timestamp
  859. }
  860. type ClientRecord struct {
  861. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  862. Email string `json:"email" gorm:"uniqueIndex;not null"`
  863. SubID string `json:"subId" gorm:"index;column:sub_id"`
  864. UUID string `json:"uuid" gorm:"column:uuid"`
  865. Password string `json:"password"`
  866. Auth string `json:"auth"`
  867. Flow string `json:"flow"`
  868. Security string `json:"security"`
  869. Reverse string `json:"reverse" gorm:"column:reverse"`
  870. PrivateKey string `json:"privateKey" gorm:"column:wg_private_key"`
  871. PublicKey string `json:"publicKey" gorm:"column:wg_public_key"`
  872. AllowedIPs string `json:"allowedIPs" gorm:"column:wg_allowed_ips"`
  873. PreSharedKey string `json:"preSharedKey" gorm:"column:wg_pre_shared_key"`
  874. KeepAlive int `json:"keepAlive" gorm:"column:wg_keep_alive;default:0"`
  875. ForwardedPorts string `json:"forwardedPorts" gorm:"column:wg_forwarded_ports"`
  876. Secret string `json:"secret" gorm:"column:secret"`
  877. AdTag string `json:"adTag" gorm:"column:ad_tag;default:''"`
  878. LimitIP int `json:"limitIp" gorm:"column:limit_ip"`
  879. LimitHwid int `json:"limitHwid" gorm:"column:limit_hwid;default:0"`
  880. TotalGB int64 `json:"totalGB" gorm:"column:total_gb"`
  881. ExpiryTime int64 `json:"expiryTime" gorm:"column:expiry_time"`
  882. Enable bool `json:"enable" gorm:"default:true"`
  883. TgID int64 `json:"tgId" gorm:"column:tg_id;index:idx_clients_tg_id"`
  884. Group string `json:"group" gorm:"column:group_name;default:'';index:idx_client_record_group"`
  885. Comment string `json:"comment"`
  886. Reset int `json:"reset" gorm:"default:0"`
  887. ResetDay int `json:"resetDay" gorm:"column:reset_day;default:0"`
  888. ResetWeekday int `json:"resetWeekday" gorm:"column:reset_weekday;default:0"`
  889. ResetMax int `json:"resetMax" gorm:"column:reset_max;default:0"`
  890. TrafficReset string `json:"trafficReset" gorm:"column:traffic_reset;default:never;index:idx_clients_traffic_reset"`
  891. TrafficResetDay int `json:"trafficResetDay" gorm:"column:traffic_reset_day;default:1"`
  892. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  893. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  894. // Owned solely by the node-snapshot sweep, which soft-orphans instead of
  895. // deleting; orphans from any other cause stay at zero and are never reaped.
  896. SyncOrphanedAt int64 `json:"-" gorm:"column:sync_orphaned_at;default:0"`
  897. }
  898. func (ClientRecord) TableName() string { return "clients" }
  899. type ClientGroup struct {
  900. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  901. Name string `json:"name" gorm:"uniqueIndex;not null"`
  902. ResetUp int64 `json:"resetUp" gorm:"column:reset_up;default:0"`
  903. ResetDown int64 `json:"resetDown" gorm:"column:reset_down;default:0"`
  904. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  905. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  906. }
  907. func (ClientGroup) TableName() string { return "client_groups" }
  908. // MarshalJSON emits the reverse column as a nested JSON object rather than an
  909. // escaped JSON-text string, matching the same convention Inbound uses for its
  910. // JSON-text columns. Empty storage renders as null.
  911. func (r ClientRecord) MarshalJSON() ([]byte, error) {
  912. type alias ClientRecord
  913. return json.Marshal(struct {
  914. alias
  915. Reverse json.RawMessage `json:"reverse"`
  916. }{
  917. alias: alias(r),
  918. Reverse: jsonStringFieldToRaw(r.Reverse),
  919. })
  920. }
  921. // UnmarshalJSON accepts reverse as either a JSON object (modern shape) or a
  922. // JSON-encoded string (legacy shape).
  923. func (r *ClientRecord) UnmarshalJSON(data []byte) error {
  924. type alias ClientRecord
  925. aux := struct {
  926. *alias
  927. Reverse json.RawMessage `json:"reverse"`
  928. }{
  929. alias: (*alias)(r),
  930. }
  931. if err := json.Unmarshal(data, &aux); err != nil {
  932. return err
  933. }
  934. r.Reverse = jsonStringFieldFromRaw(aux.Reverse)
  935. return nil
  936. }
  937. type ClientInbound struct {
  938. ClientId int `json:"clientId" gorm:"primaryKey;column:client_id;index"`
  939. InboundId int `json:"inboundId" gorm:"primaryKey;column:inbound_id;index"`
  940. FlowOverride string `json:"flowOverride" gorm:"column:flow_override"`
  941. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  942. }
  943. func (ClientInbound) TableName() string { return "client_inbounds" }
  944. type ClientHwid struct {
  945. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  946. SubID string `json:"subId" gorm:"column:sub_id;not null;index;uniqueIndex:idx_client_hwids_sub_hash,priority:1"`
  947. HwidHash string `json:"-" gorm:"column:hwid_hash;size:64;not null;uniqueIndex:idx_client_hwids_sub_hash,priority:2"`
  948. FirstSeen int64 `json:"firstSeen" gorm:"column:first_seen;not null"`
  949. LastSeen int64 `json:"lastSeen" gorm:"column:last_seen;not null;index"`
  950. UserAgent string `json:"userAgent" gorm:"column:user_agent"`
  951. DeviceOS string `json:"deviceOs" gorm:"column:device_os"`
  952. OsVersion string `json:"osVersion" gorm:"column:os_version"`
  953. DeviceModel string `json:"deviceModel" gorm:"column:device_model"`
  954. }
  955. func (ClientHwid) TableName() string { return "client_hwids" }
  956. // ClientExternalLink is a per-client entry surfaced in the client's
  957. // subscription. Two kinds:
  958. // - "link": a single third-party share link (vless://, vmess://, trojan://,
  959. // ss://, hysteria2://, wireguard://). Emitted verbatim in raw subs; parsed
  960. // into an outbound/proxy for JSON and Clash.
  961. // - "subscription": a remote subscription URL. The panel fetches it (cached),
  962. // decodes its links, and merges them into the client's subscription.
  963. type ClientExternalLink struct {
  964. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  965. ClientId int `json:"clientId" gorm:"index;column:client_id"`
  966. Kind string `json:"kind" gorm:"column:kind"`
  967. Value string `json:"value" gorm:"column:value"`
  968. Remark string `json:"remark" gorm:"column:remark"`
  969. Enable *bool `json:"enable" gorm:"column:enable;default:true"`
  970. ExpiryTime int64 `json:"expiryTime" gorm:"column:expiry_time;default:0"`
  971. NamePrefix string `json:"namePrefix" gorm:"column:name_prefix"`
  972. LastFetchAt int64 `json:"lastFetchAt" gorm:"column:last_fetch_at;default:0"`
  973. LastFetchError string `json:"lastFetchError" gorm:"column:last_fetch_error"`
  974. SortIndex int `json:"sortIndex" gorm:"column:sort_index"`
  975. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  976. }
  977. func (ClientExternalLink) TableName() string { return "client_external_links" }
  978. // External link kinds.
  979. const (
  980. ExternalLinkKindLink = "link"
  981. ExternalLinkKindSubscription = "subscription"
  982. )
  983. type InboundFallback struct {
  984. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  985. MasterId int `json:"masterId" gorm:"index;not null;column:master_id"`
  986. ChildId int `json:"childId" gorm:"index;not null;column:child_id"`
  987. Name string `json:"name"`
  988. Alpn string `json:"alpn"`
  989. Path string `json:"path"`
  990. Dest string `json:"dest"`
  991. Xver int `json:"xver"`
  992. SortOrder int `json:"sortOrder" gorm:"default:0;column:sort_order"`
  993. }
  994. func (InboundFallback) TableName() string { return "inbound_fallbacks" }
  995. type Host struct {
  996. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement" example:"1"`
  997. GroupId string `json:"groupId" form:"groupId" gorm:"column:group_id;index"`
  998. InboundId int `json:"inboundId" form:"inboundId" gorm:"index;not null;column:inbound_id" validate:"required" example:"1"`
  999. SortOrder int `json:"sortOrder" form:"sortOrder" gorm:"default:0;column:sort_order"`
  1000. Remark string `json:"remark" form:"remark" validate:"required,max=256" example:"cdn-front"`
  1001. ServerDescription string `json:"serverDescription" form:"serverDescription" gorm:"column:server_description" validate:"omitempty,max=64"`
  1002. IsDisabled bool `json:"isDisabled" form:"isDisabled" gorm:"default:false;column:is_disabled"`
  1003. IsHidden bool `json:"isHidden" form:"isHidden" gorm:"default:false;column:is_hidden"`
  1004. Tags []string `json:"tags" form:"tags" gorm:"serializer:json"`
  1005. Address string `json:"address" form:"address" example:"cdn.example.com"`
  1006. Port int `json:"port" form:"port" gorm:"default:0" validate:"gte=0,lte=65535" example:"8443"`
  1007. Security string `json:"security" form:"security" gorm:"default:same" validate:"omitempty,oneof=same tls none reality" example:"same"`
  1008. Sni string `json:"sni" form:"sni"`
  1009. HostHeader string `json:"hostHeader" form:"hostHeader" gorm:"column:host_header"`
  1010. Path string `json:"path" form:"path"`
  1011. Alpn []string `json:"alpn" form:"alpn" gorm:"serializer:json"`
  1012. Fingerprint string `json:"fingerprint" form:"fingerprint"`
  1013. CipherSuites string `json:"cipherSuites" form:"cipherSuites" gorm:"column:cipher_suites"`
  1014. OverrideSniFromAddress bool `json:"overrideSniFromAddress" form:"overrideSniFromAddress" gorm:"column:override_sni_from_address"`
  1015. KeepSniBlank bool `json:"keepSniBlank" form:"keepSniBlank" gorm:"column:keep_sni_blank"`
  1016. PinnedPeerCertSha256 []string `json:"pinnedPeerCertSha256" form:"pinnedPeerCertSha256" gorm:"serializer:json;column:pinned_peer_cert_sha256"`
  1017. VerifyPeerCertByName string `json:"verifyPeerCertByName" form:"verifyPeerCertByName" gorm:"column:verify_peer_cert_by_name"`
  1018. AllowInsecure bool `json:"allowInsecure" form:"allowInsecure" gorm:"column:allow_insecure"`
  1019. EchConfigList string `json:"echConfigList" form:"echConfigList" gorm:"column:ech_config_list"`
  1020. MuxParams string `json:"muxParams" form:"muxParams" gorm:"type:text;column:mux_params"`
  1021. SockoptParams string `json:"sockoptParams" form:"sockoptParams" gorm:"type:text;column:sockopt_params"`
  1022. // FinalMask is a JSON object of xray finalmask masks (tcp/udp/quicParams),
  1023. // merged into this host's JSON-subscription stream. Empty = no override.
  1024. FinalMask string `json:"finalMask" form:"finalMask" gorm:"type:text;column:final_mask"`
  1025. // Single VLESS route value (0-65535) baked into the subscription UUID's 3rd
  1026. // group (bytes 6-7), which xray reads via net.PortFromBytes(id[6:8]). Empty = none.
  1027. VlessRoute string `json:"vlessRoute" form:"vlessRoute" gorm:"column:vless_route" example:"443"`
  1028. ExcludeFromSubTypes []string `json:"excludeFromSubTypes" form:"excludeFromSubTypes" gorm:"serializer:json;column:exclude_from_sub_types"`
  1029. MihomoIpVersion string `json:"mihomoIpVersion" form:"mihomoIpVersion" gorm:"column:mihomo_ip_version" validate:"omitempty,oneof=dual ipv4 ipv6 ipv4-prefer ipv6-prefer"`
  1030. MihomoX25519 bool `json:"mihomoX25519" form:"mihomoX25519" gorm:"column:mihomo_x25519"`
  1031. ShuffleHost bool `json:"shuffleHost" form:"shuffleHost" gorm:"column:shuffle_host"`
  1032. NodeGuids []string `json:"nodeGuids,omitempty" form:"nodeGuids" gorm:"serializer:json;column:node_guids"`
  1033. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  1034. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  1035. }
  1036. func (Host) TableName() string { return "hosts" }
  1037. // KeepAliveSeconds is the client's PersistentKeepalive, 0 when unset.
  1038. func (c Client) KeepAliveSeconds() int {
  1039. if c.KeepAlive == nil {
  1040. return 0
  1041. }
  1042. return *c.KeepAlive
  1043. }
  1044. // KeepAlivePtr wraps an explicit PersistentKeepalive, 0 included -- distinct
  1045. // from a nil KeepAlive, which means the field was never sent.
  1046. func KeepAlivePtr(v int) *int { return &v }
  1047. // nonZeroKeepAlive keeps a stored 0 nil: wg_keep_alive cannot tell "off" from
  1048. // "never set", and an explicit 0 would emit keepAlive on every protocol.
  1049. func nonZeroKeepAlive(seconds int) *int {
  1050. if seconds <= 0 {
  1051. return nil
  1052. }
  1053. return KeepAlivePtr(seconds)
  1054. }
  1055. func (c *Client) ToRecord() *ClientRecord {
  1056. rec := &ClientRecord{
  1057. Email: c.Email,
  1058. SubID: c.SubID,
  1059. UUID: c.ID,
  1060. Password: c.Password,
  1061. Auth: c.Auth,
  1062. Flow: c.Flow,
  1063. Security: c.Security,
  1064. LimitIP: c.LimitIP,
  1065. TotalGB: c.TotalGB,
  1066. ExpiryTime: c.ExpiryTime,
  1067. Enable: c.Enable,
  1068. TgID: c.TgID,
  1069. Group: c.Group,
  1070. Comment: c.Comment,
  1071. Reset: c.Reset,
  1072. ResetDay: c.ResetDay,
  1073. ResetWeekday: c.ResetWeekday,
  1074. ResetMax: c.ResetMax,
  1075. TrafficReset: c.TrafficReset,
  1076. TrafficResetDay: c.TrafficResetDay,
  1077. CreatedAt: c.CreatedAt,
  1078. UpdatedAt: c.UpdatedAt,
  1079. PrivateKey: c.PrivateKey,
  1080. PublicKey: c.PublicKey,
  1081. AllowedIPs: strings.Join(c.AllowedIPs, ","),
  1082. PreSharedKey: c.PreSharedKey,
  1083. KeepAlive: c.KeepAliveSeconds(),
  1084. ForwardedPorts: c.ForwardedPorts,
  1085. Secret: c.Secret,
  1086. AdTag: c.AdTag,
  1087. }
  1088. if c.Reverse != nil {
  1089. if b, err := json.Marshal(c.Reverse); err == nil {
  1090. rec.Reverse = string(b)
  1091. }
  1092. }
  1093. return rec
  1094. }
  1095. func splitWireguardAllowedIPs(csv string) []string {
  1096. if csv == "" {
  1097. return nil
  1098. }
  1099. parts := strings.Split(csv, ",")
  1100. out := make([]string, 0, len(parts))
  1101. for _, p := range parts {
  1102. if trimmed := strings.TrimSpace(p); trimmed != "" {
  1103. out = append(out, trimmed)
  1104. }
  1105. }
  1106. if len(out) == 0 {
  1107. return nil
  1108. }
  1109. return out
  1110. }
  1111. func (r *ClientRecord) ToClient() *Client {
  1112. c := &Client{
  1113. ID: r.UUID,
  1114. Email: r.Email,
  1115. SubID: r.SubID,
  1116. Password: r.Password,
  1117. Auth: r.Auth,
  1118. Flow: r.Flow,
  1119. Security: r.Security,
  1120. LimitIP: r.LimitIP,
  1121. TotalGB: r.TotalGB,
  1122. ExpiryTime: r.ExpiryTime,
  1123. Enable: r.Enable,
  1124. TgID: r.TgID,
  1125. Group: r.Group,
  1126. Comment: r.Comment,
  1127. Reset: r.Reset,
  1128. ResetDay: r.ResetDay,
  1129. ResetWeekday: r.ResetWeekday,
  1130. ResetMax: r.ResetMax,
  1131. TrafficReset: r.TrafficReset,
  1132. TrafficResetDay: r.TrafficResetDay,
  1133. CreatedAt: r.CreatedAt,
  1134. UpdatedAt: r.UpdatedAt,
  1135. PrivateKey: r.PrivateKey,
  1136. PublicKey: r.PublicKey,
  1137. AllowedIPs: splitWireguardAllowedIPs(r.AllowedIPs),
  1138. PreSharedKey: r.PreSharedKey,
  1139. KeepAlive: nonZeroKeepAlive(r.KeepAlive),
  1140. ForwardedPorts: r.ForwardedPorts,
  1141. Secret: r.Secret,
  1142. AdTag: r.AdTag,
  1143. }
  1144. if r.Reverse != "" {
  1145. var rev ClientReverse
  1146. if err := json.Unmarshal([]byte(r.Reverse), &rev); err == nil {
  1147. c.Reverse = &rev
  1148. }
  1149. }
  1150. return c
  1151. }
  1152. type ClientMergeConflict struct {
  1153. Field string
  1154. Old any
  1155. New any
  1156. Kept any
  1157. }
  1158. type OutboundSubscription struct {
  1159. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
  1160. Remark string `json:"remark" form:"remark"`
  1161. Url string `json:"url" form:"url"`
  1162. Enabled bool `json:"enabled" form:"enabled" gorm:"default:true"`
  1163. AllowPrivate bool `json:"allowPrivate" form:"allowPrivate" gorm:"default:false"`
  1164. AllowInsecure bool `json:"allowInsecure" form:"allowInsecure" gorm:"default:false"`
  1165. UserAgent string `json:"userAgent" form:"userAgent"`
  1166. TagPrefix string `json:"tagPrefix" form:"tagPrefix"`
  1167. UpdateInterval int `json:"updateInterval" form:"updateInterval" gorm:"default:600"` // seconds between refreshes
  1168. Priority int `json:"priority" form:"priority" gorm:"default:0"` // order among subscriptions in the merged outbounds (lower = earlier)
  1169. Prepend bool `json:"prepend" form:"prepend" gorm:"default:false"` // place this subscription's outbounds before the manual template outbounds
  1170. LastUpdated int64 `json:"lastUpdated" form:"lastUpdated"`
  1171. LastError string `json:"lastError" form:"lastError"`
  1172. LastFetchedOutbounds string `json:"lastFetchedOutbounds" form:"lastFetchedOutbounds" gorm:"type:text"`
  1173. LinkIdentities string `json:"-" gorm:"type:text;column:link_identities"`
  1174. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  1175. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  1176. OutboundCount int `json:"outboundCount" gorm:"-"`
  1177. }
  1178. // SubBalancer is one extra JSON-subscription config document whose members are
  1179. // the selected inbounds' proxy outbounds. SortOrder shares SubSortIndex semantics.
  1180. type SubBalancer struct {
  1181. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement" example:"1"`
  1182. Remark string `json:"remark" form:"remark" validate:"required,max=256" example:"auto-fastest"`
  1183. Strategy string `json:"strategy" form:"strategy" validate:"omitempty,oneof=leastLoad leastPing random roundRobin" example:"random"`
  1184. InboundIds []int `json:"inboundIds" form:"inboundIds" gorm:"serializer:json;column:inbound_ids" example:"[1,3]"`
  1185. // inboundId -> leastLoad weight; absent entries mean 1.0. Only meaningful
  1186. // with Strategy "leastLoad" — xray ignores costs on every other strategy.
  1187. MemberWeights map[int]float64 `json:"memberWeights,omitempty" form:"memberWeights" gorm:"serializer:json;column:member_weights"`
  1188. SortOrder int `json:"sortOrder" form:"sortOrder" gorm:"column:sort_order" validate:"omitempty,gte=1" example:"1"`
  1189. // No gorm default:true — a bool default makes an explicit false at insert
  1190. // collapse back to the column default (zero value is skipped).
  1191. Enabled bool `json:"enabled" form:"enabled" example:"true"`
  1192. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli" example:"1710000000000"`
  1193. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli" example:"1710000000000"`
  1194. }
  1195. func MergeClientRecord(existing *ClientRecord, incoming *ClientRecord) []ClientMergeConflict {
  1196. var conflicts []ClientMergeConflict
  1197. keep := func(field string, oldV, newV, kept any) {
  1198. conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: oldV, New: newV, Kept: kept})
  1199. }
  1200. const redacted = "<redacted>"
  1201. keepSecret := func(field string) {
  1202. conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: redacted, New: redacted, Kept: redacted})
  1203. }
  1204. incomingNewer := incoming.UpdatedAt > existing.UpdatedAt ||
  1205. (incoming.UpdatedAt == existing.UpdatedAt && incoming.CreatedAt > existing.CreatedAt)
  1206. if existing.UUID != incoming.UUID && incoming.UUID != "" {
  1207. if incomingNewer || existing.UUID == "" {
  1208. existing.UUID = incoming.UUID
  1209. }
  1210. keepSecret("uuid")
  1211. }
  1212. if existing.Password != incoming.Password && incoming.Password != "" {
  1213. if incomingNewer || existing.Password == "" {
  1214. existing.Password = incoming.Password
  1215. keepSecret("password")
  1216. }
  1217. }
  1218. if existing.Auth != incoming.Auth && incoming.Auth != "" {
  1219. if incomingNewer || existing.Auth == "" {
  1220. existing.Auth = incoming.Auth
  1221. keepSecret("auth")
  1222. }
  1223. }
  1224. if existing.Flow != incoming.Flow && incoming.Flow != "" {
  1225. if incomingNewer || existing.Flow == "" {
  1226. keep("flow", existing.Flow, incoming.Flow, incoming.Flow)
  1227. existing.Flow = incoming.Flow
  1228. }
  1229. }
  1230. if existing.Security != incoming.Security && incoming.Security != "" {
  1231. if incomingNewer || existing.Security == "" {
  1232. keep("security", existing.Security, incoming.Security, incoming.Security)
  1233. existing.Security = incoming.Security
  1234. }
  1235. }
  1236. if existing.SubID != incoming.SubID && incoming.SubID != "" {
  1237. if incomingNewer || existing.SubID == "" {
  1238. existing.SubID = incoming.SubID
  1239. keepSecret("subId")
  1240. }
  1241. }
  1242. if existing.TotalGB != incoming.TotalGB {
  1243. picked := existing.TotalGB
  1244. if existing.TotalGB == 0 || (incoming.TotalGB != 0 && incoming.TotalGB > existing.TotalGB) {
  1245. picked = incoming.TotalGB
  1246. }
  1247. if picked != existing.TotalGB {
  1248. keep("totalGB", existing.TotalGB, incoming.TotalGB, picked)
  1249. existing.TotalGB = picked
  1250. }
  1251. }
  1252. if existing.ExpiryTime != incoming.ExpiryTime {
  1253. picked := existing.ExpiryTime
  1254. if existing.ExpiryTime == 0 || (incoming.ExpiryTime != 0 && incoming.ExpiryTime > existing.ExpiryTime) {
  1255. picked = incoming.ExpiryTime
  1256. }
  1257. if picked != existing.ExpiryTime {
  1258. keep("expiryTime", existing.ExpiryTime, incoming.ExpiryTime, picked)
  1259. existing.ExpiryTime = picked
  1260. }
  1261. }
  1262. if existing.LimitIP != incoming.LimitIP && incoming.LimitIP != 0 {
  1263. picked := existing.LimitIP
  1264. if existing.LimitIP == 0 || incoming.LimitIP > existing.LimitIP {
  1265. picked = incoming.LimitIP
  1266. }
  1267. if picked != existing.LimitIP {
  1268. keep("limitIp", existing.LimitIP, incoming.LimitIP, picked)
  1269. existing.LimitIP = picked
  1270. }
  1271. }
  1272. if existing.LimitHwid != incoming.LimitHwid && incoming.LimitHwid != 0 {
  1273. picked := existing.LimitHwid
  1274. if existing.LimitHwid == 0 || incoming.LimitHwid > existing.LimitHwid {
  1275. picked = incoming.LimitHwid
  1276. }
  1277. if picked != existing.LimitHwid {
  1278. keep("limitHwid", existing.LimitHwid, incoming.LimitHwid, picked)
  1279. existing.LimitHwid = picked
  1280. }
  1281. }
  1282. if existing.TgID != incoming.TgID && incoming.TgID != 0 {
  1283. if incomingNewer || existing.TgID == 0 {
  1284. keep("tgId", existing.TgID, incoming.TgID, incoming.TgID)
  1285. existing.TgID = incoming.TgID
  1286. }
  1287. }
  1288. if existing.ResetWeekday != 0 || incoming.ResetWeekday != 0 {
  1289. // A mode switch must carry its zeroes, not fill them from another mode.
  1290. // Empty snapshots still preserve the existing schedule during migration.
  1291. incomingSet := incoming.Reset != 0 || incoming.ResetDay != 0 || incoming.ResetWeekday != 0
  1292. existingSet := existing.Reset != 0 || existing.ResetDay != 0 || existing.ResetWeekday != 0
  1293. if incomingSet && (incomingNewer || !existingSet) {
  1294. for _, field := range []struct {
  1295. name string
  1296. current *int
  1297. value int
  1298. }{
  1299. {"reset", &existing.Reset, incoming.Reset},
  1300. {"resetDay", &existing.ResetDay, incoming.ResetDay},
  1301. {"resetWeekday", &existing.ResetWeekday, incoming.ResetWeekday},
  1302. } {
  1303. if *field.current != field.value {
  1304. keep(field.name, *field.current, field.value, field.value)
  1305. *field.current = field.value
  1306. }
  1307. }
  1308. }
  1309. } else {
  1310. if existing.Reset != incoming.Reset && incoming.Reset != 0 {
  1311. if incomingNewer || existing.Reset == 0 {
  1312. keep("reset", existing.Reset, incoming.Reset, incoming.Reset)
  1313. existing.Reset = incoming.Reset
  1314. }
  1315. }
  1316. if existing.ResetDay != incoming.ResetDay && incoming.ResetDay != 0 {
  1317. if incomingNewer || existing.ResetDay == 0 {
  1318. keep("resetDay", existing.ResetDay, incoming.ResetDay, incoming.ResetDay)
  1319. existing.ResetDay = incoming.ResetDay
  1320. }
  1321. }
  1322. }
  1323. if existing.ResetMax != incoming.ResetMax && incoming.ResetMax != 0 {
  1324. if incomingNewer || existing.ResetMax == 0 {
  1325. keep("resetMax", existing.ResetMax, incoming.ResetMax, incoming.ResetMax)
  1326. existing.ResetMax = incoming.ResetMax
  1327. }
  1328. }
  1329. if existing.TrafficReset != incoming.TrafficReset && incoming.TrafficReset != "" {
  1330. if incomingNewer || existing.TrafficReset == "" {
  1331. keep("trafficReset", existing.TrafficReset, incoming.TrafficReset, incoming.TrafficReset)
  1332. existing.TrafficReset = incoming.TrafficReset
  1333. }
  1334. }
  1335. if existing.TrafficResetDay != incoming.TrafficResetDay && incoming.TrafficResetDay != 0 {
  1336. if incomingNewer || existing.TrafficResetDay == 0 {
  1337. keep("trafficResetDay", existing.TrafficResetDay, incoming.TrafficResetDay, incoming.TrafficResetDay)
  1338. existing.TrafficResetDay = incoming.TrafficResetDay
  1339. }
  1340. }
  1341. if existing.Reverse != incoming.Reverse && incoming.Reverse != "" {
  1342. if incomingNewer || existing.Reverse == "" {
  1343. keep("reverse", existing.Reverse, incoming.Reverse, incoming.Reverse)
  1344. existing.Reverse = incoming.Reverse
  1345. }
  1346. }
  1347. if existing.PrivateKey != incoming.PrivateKey && incoming.PrivateKey != "" {
  1348. if incomingNewer || existing.PrivateKey == "" {
  1349. existing.PrivateKey = incoming.PrivateKey
  1350. keepSecret("privateKey")
  1351. }
  1352. }
  1353. if existing.PublicKey != incoming.PublicKey && incoming.PublicKey != "" {
  1354. if incomingNewer || existing.PublicKey == "" {
  1355. existing.PublicKey = incoming.PublicKey
  1356. keepSecret("publicKey")
  1357. }
  1358. }
  1359. if existing.PreSharedKey != incoming.PreSharedKey && incoming.PreSharedKey != "" {
  1360. if incomingNewer || existing.PreSharedKey == "" {
  1361. existing.PreSharedKey = incoming.PreSharedKey
  1362. keepSecret("preSharedKey")
  1363. }
  1364. }
  1365. if existing.Secret != incoming.Secret && incoming.Secret != "" {
  1366. if incomingNewer || existing.Secret == "" {
  1367. existing.Secret = incoming.Secret
  1368. keepSecret("secret")
  1369. }
  1370. }
  1371. if existing.AllowedIPs != incoming.AllowedIPs && incoming.AllowedIPs != "" {
  1372. if incomingNewer || existing.AllowedIPs == "" {
  1373. keep("allowedIPs", existing.AllowedIPs, incoming.AllowedIPs, incoming.AllowedIPs)
  1374. existing.AllowedIPs = incoming.AllowedIPs
  1375. }
  1376. }
  1377. if existing.KeepAlive != incoming.KeepAlive && incoming.KeepAlive != 0 {
  1378. if incomingNewer || existing.KeepAlive == 0 {
  1379. keep("keepAlive", existing.KeepAlive, incoming.KeepAlive, incoming.KeepAlive)
  1380. existing.KeepAlive = incoming.KeepAlive
  1381. }
  1382. }
  1383. if existing.ForwardedPorts != incoming.ForwardedPorts && incoming.ForwardedPorts != "" {
  1384. if incomingNewer || existing.ForwardedPorts == "" {
  1385. keep("forwardedPorts", existing.ForwardedPorts, incoming.ForwardedPorts, incoming.ForwardedPorts)
  1386. existing.ForwardedPorts = incoming.ForwardedPorts
  1387. }
  1388. }
  1389. if existing.Comment != incoming.Comment && incoming.Comment != "" {
  1390. if incomingNewer || existing.Comment == "" {
  1391. keep("comment", existing.Comment, incoming.Comment, incoming.Comment)
  1392. existing.Comment = incoming.Comment
  1393. }
  1394. }
  1395. if existing.Group != incoming.Group && incoming.Group != "" {
  1396. if incomingNewer || existing.Group == "" {
  1397. keep("group", existing.Group, incoming.Group, incoming.Group)
  1398. existing.Group = incoming.Group
  1399. }
  1400. }
  1401. if existing.Enable != incoming.Enable {
  1402. if incoming.Enable {
  1403. if !existing.Enable {
  1404. keep("enable", existing.Enable, incoming.Enable, true)
  1405. existing.Enable = true
  1406. }
  1407. }
  1408. }
  1409. if incoming.CreatedAt != 0 && (existing.CreatedAt == 0 || incoming.CreatedAt < existing.CreatedAt) {
  1410. existing.CreatedAt = incoming.CreatedAt
  1411. }
  1412. if incoming.UpdatedAt > existing.UpdatedAt {
  1413. existing.UpdatedAt = incoming.UpdatedAt
  1414. }
  1415. return conflicts
  1416. }