model.go 64 KB

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