model.go 50 KB

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