model.go 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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. // ReplaceRemovedShadowsocksCipher maps ciphers that xray-core v26.7.11
  418. // deleted ("none"/"plain" make the whole config fail with "unknown cipher
  419. // method") to a still-supported replacement. Returns the replacement and
  420. // true when the given method is one of the removed ciphers.
  421. func ReplaceRemovedShadowsocksCipher(method string) (string, bool) {
  422. switch method {
  423. case "none", "plain":
  424. return "chacha20-ietf-poly1305", true
  425. }
  426. return method, false
  427. }
  428. // HealShadowsocksClientMethods normalises the `method` fields on a
  429. // shadowsocks inbound's settings JSON before it leaves for xray-core:
  430. // - Ciphers removed upstream (none/plain): rewritten via
  431. // ReplaceRemovedShadowsocksCipher so one legacy row cannot prevent
  432. // xray from starting.
  433. // - Legacy ciphers (aes-*, chacha20-*): every client must carry a
  434. // per-user `method` matching the inbound's top-level method, otherwise
  435. // xray fails with "unsupported cipher method:".
  436. // - Shadowsocks 2022 (2022-blake3-*): xray's multi-user code rejects the
  437. // inbound with "users must have empty method" when a client carries
  438. // one — strip stale entries left over from a switch off a legacy
  439. // cipher.
  440. //
  441. // Returns the rewritten settings string and true when anything changed.
  442. func HealShadowsocksClientMethods(settings string) (string, bool) {
  443. if settings == "" {
  444. return settings, false
  445. }
  446. var parsed map[string]any
  447. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  448. return settings, false
  449. }
  450. method, _ := parsed["method"].(string)
  451. changed := false
  452. if replacement, removed := ReplaceRemovedShadowsocksCipher(method); removed {
  453. method = replacement
  454. parsed["method"] = method
  455. changed = true
  456. }
  457. clients, ok := parsed["clients"].([]any)
  458. if !ok {
  459. if !changed {
  460. return settings, false
  461. }
  462. out, err := json.MarshalIndent(parsed, "", " ")
  463. if err != nil {
  464. return settings, false
  465. }
  466. return string(out), true
  467. }
  468. is2022 := strings.HasPrefix(method, "2022-blake3-")
  469. for i := range clients {
  470. cm, ok := clients[i].(map[string]any)
  471. if !ok {
  472. continue
  473. }
  474. if is2022 {
  475. if _, hasKey := cm["method"]; hasKey {
  476. delete(cm, "method")
  477. clients[i] = cm
  478. changed = true
  479. }
  480. continue
  481. }
  482. if method == "" {
  483. continue
  484. }
  485. existing, _ := cm["method"].(string)
  486. if existing == method {
  487. continue
  488. }
  489. cm["method"] = method
  490. clients[i] = cm
  491. changed = true
  492. }
  493. if !changed {
  494. return settings, false
  495. }
  496. out, err := json.MarshalIndent(parsed, "", " ")
  497. if err != nil {
  498. return settings, false
  499. }
  500. return string(out), true
  501. }
  502. // GenerateFakeTLSSecret builds an MTProto FakeTLS secret for the given domain:
  503. // the "ee" FakeTLS marker, 16 random bytes, then the domain encoded as hex.
  504. // MTProto is multi-client, so this value belongs to one client: mtg's [secrets]
  505. // config and that client's tg:// link both read it per client.
  506. func GenerateFakeTLSSecret(domain string) string {
  507. return "ee" + mtprotoRandomMiddle() + hex.EncodeToString([]byte(domain))
  508. }
  509. func mtprotoRandomMiddle() string {
  510. buf := make([]byte, 16)
  511. if _, err := rand.Read(buf); err != nil {
  512. panic(fmt.Errorf("mtproto: crypto/rand read failed: %w", err))
  513. }
  514. return hex.EncodeToString(buf)
  515. }
  516. // mtprotoSecretMiddle returns the 16-byte random middle of an existing secret
  517. // when it is well-formed, otherwise a freshly generated one. Reusing the middle
  518. // keeps the secret stable when only the FakeTLS domain changes.
  519. func mtprotoSecretMiddle(secret string) string {
  520. s := secret
  521. if strings.HasPrefix(s, "ee") || strings.HasPrefix(s, "dd") {
  522. s = s[2:]
  523. }
  524. if len(s) >= 32 {
  525. mid := s[:32]
  526. if _, err := hex.DecodeString(mid); err == nil {
  527. return mid
  528. }
  529. }
  530. return mtprotoRandomMiddle()
  531. }
  532. // ValidMtprotoAdTag reports whether a Telegram advertising tag from
  533. // @MTProxybot is well-formed: exactly 16 bytes as 32 hex characters. mtg
  534. // refuses to start (or rejects a live update) on a malformed tag, so every
  535. // write path validates before the tag can reach a generated config.
  536. func ValidMtprotoAdTag(tag string) bool {
  537. if len(tag) != 32 {
  538. return false
  539. }
  540. _, err := hex.DecodeString(tag)
  541. return err == nil
  542. }
  543. // StripMtprotoInboundSecret removes the vestigial inbound-level `secret` from an
  544. // mtproto inbound's settings JSON. MTProto is multi-client: every secret lives on
  545. // a client, and mtg's [secrets] config plus every share link read only the
  546. // per-client secrets. A lingering inbound-level secret is dead data — it once
  547. // leaked into stale links that mtg rejected as "incorrect client random". Returns
  548. // the rewritten settings and true when a `secret` key was removed.
  549. func StripMtprotoInboundSecret(settings string) (string, bool) {
  550. if settings == "" {
  551. return settings, false
  552. }
  553. var parsed map[string]any
  554. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  555. return settings, false
  556. }
  557. if _, ok := parsed["secret"]; !ok {
  558. return settings, false
  559. }
  560. delete(parsed, "secret")
  561. out, err := json.MarshalIndent(parsed, "", " ")
  562. if err != nil {
  563. return settings, false
  564. }
  565. return string(out), true
  566. }
  567. // StripMtprotoInboundAdTag drops the dead inbound-level `adTag` — tags live on clients.
  568. func StripMtprotoInboundAdTag(settings string) (string, bool) {
  569. if settings == "" {
  570. return settings, false
  571. }
  572. var parsed map[string]any
  573. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  574. return settings, false
  575. }
  576. if _, ok := parsed["adTag"]; !ok {
  577. return settings, false
  578. }
  579. delete(parsed, "adTag")
  580. out, err := json.MarshalIndent(parsed, "", " ")
  581. if err != nil {
  582. return settings, false
  583. }
  584. return string(out), true
  585. }
  586. // mtprotoSecretDomain extracts the FakeTLS domain embedded in the tail of a
  587. // secret, returning an empty string when the secret is malformed. Each mtproto
  588. // client carries its own domain inside its secret, so healing preserves it
  589. // instead of forcing every client onto the inbound-level default.
  590. func mtprotoSecretDomain(secret string) string {
  591. s := secret
  592. if strings.HasPrefix(s, "ee") || strings.HasPrefix(s, "dd") {
  593. s = s[2:]
  594. }
  595. if len(s) <= 32 {
  596. return ""
  597. }
  598. decoded, err := hex.DecodeString(s[32:])
  599. if err != nil || len(decoded) == 0 {
  600. return ""
  601. }
  602. return string(decoded)
  603. }
  604. // HealMtprotoClientSecrets normalises every client's FakeTLS secret in an
  605. // mtproto inbound's settings JSON: each secret is rebuilt so it stays a valid
  606. // FakeTLS value, keeping the client's own embedded domain when present and
  607. // falling back to the inbound-level fakeTlsDomain otherwise. Returns the
  608. // rewritten settings and true when anything changed.
  609. func HealMtprotoClientSecrets(settings string) (string, bool) {
  610. if settings == "" {
  611. return settings, false
  612. }
  613. var parsed map[string]any
  614. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  615. return settings, false
  616. }
  617. clients, ok := parsed["clients"].([]any)
  618. if !ok || len(clients) == 0 {
  619. return settings, false
  620. }
  621. defaultDomain, _ := parsed["fakeTlsDomain"].(string)
  622. defaultDomain = strings.TrimSpace(defaultDomain)
  623. changed := false
  624. for _, raw := range clients {
  625. client, ok := raw.(map[string]any)
  626. if !ok {
  627. continue
  628. }
  629. secret, _ := client["secret"].(string)
  630. domain := mtprotoSecretDomain(secret)
  631. if domain == "" {
  632. domain = defaultDomain
  633. }
  634. if domain == "" {
  635. continue
  636. }
  637. expected := "ee" + mtprotoSecretMiddle(secret) + hex.EncodeToString([]byte(domain))
  638. if secret != expected {
  639. client["secret"] = expected
  640. changed = true
  641. }
  642. }
  643. if !changed {
  644. return settings, false
  645. }
  646. out, err := json.MarshalIndent(parsed, "", " ")
  647. if err != nil {
  648. return settings, false
  649. }
  650. return string(out), true
  651. }
  652. // Setting stores key-value configuration settings for the 3x-ui panel.
  653. type Setting struct {
  654. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
  655. Key string `json:"key" form:"key" gorm:"index:idx_settings_key"`
  656. Value string `json:"value" form:"value"`
  657. }
  658. // Node represents a remote 3x-ui panel registered with the central panel.
  659. // The central panel polls each node's existing /panel/api/server/status
  660. // endpoint over HTTP using the per-node ApiToken to populate the runtime
  661. // status fields below.
  662. type Node struct {
  663. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement" example:"1"`
  664. Name string `json:"name" form:"name" gorm:"uniqueIndex" validate:"required" example:"de-fra-1"`
  665. Remark string `json:"remark" form:"remark"`
  666. Scheme string `json:"scheme" form:"scheme" validate:"omitempty,oneof=http https" example:"https"`
  667. Address string `json:"address" form:"address" validate:"required" example:"node1.example.com"`
  668. Port int `json:"port" form:"port" validate:"gte=1,lte=65535" example:"2053"`
  669. BasePath string `json:"basePath" form:"basePath" example:"/"`
  670. ApiToken string `json:"apiToken" form:"apiToken" validate:"required_unless=TlsVerifyMode mtls" example:"abcdef0123456789"`
  671. Enable bool `json:"enable" form:"enable" gorm:"default:true" example:"true"`
  672. AllowPrivateAddress bool `json:"allowPrivateAddress" form:"allowPrivateAddress" gorm:"default:false"`
  673. TlsVerifyMode string `json:"tlsVerifyMode" form:"tlsVerifyMode" gorm:"column:tls_verify_mode;default:verify" validate:"omitempty,oneof=verify skip pin mtls"`
  674. PinnedCertSha256 string `json:"pinnedCertSha256" form:"pinnedCertSha256" gorm:"column:pinned_cert_sha256"`
  675. InboundSyncMode string `json:"inboundSyncMode" form:"inboundSyncMode" gorm:"column:inbound_sync_mode;default:all" validate:"omitempty,oneof=all selected"`
  676. InboundTags []string `json:"inboundTags" form:"inboundTags" gorm:"serializer:json;column:inbound_tags"`
  677. OutboundTag string `json:"outboundTag" form:"outboundTag" gorm:"column:outbound_tag"`
  678. // Guid is the remote panel's stable self-identifier (its panelGuid),
  679. // learned from each heartbeat. It is the globally stable node identity used
  680. // to attribute online clients/inbounds to the physical node across a chain
  681. // of nodes (#4983); panel-local autoincrement ids don't survive a hop.
  682. // Observed-state only — never user-edited.
  683. Guid string `json:"guid" gorm:"column:guid;index"`
  684. // Heartbeat-updated fields. UpdatedAt advances on every probe even when
  685. // the row is otherwise unchanged so the UI's "last seen" tooltip is
  686. // truthful without us having to read LastHeartbeat separately.
  687. Status string `json:"status" gorm:"default:unknown" example:"online"` // online|offline|unknown
  688. LastHeartbeat int64 `json:"lastHeartbeat" example:"1700000000"` // unix seconds, 0 = never
  689. LatencyMs int `json:"latencyMs" example:"42"`
  690. XrayVersion string `json:"xrayVersion" example:"25.10.31"`
  691. PanelVersion string `json:"panelVersion" gorm:"column:panel_version" example:"v3.x.x"`
  692. CpuPct float64 `json:"cpuPct" example:"23.5"`
  693. MemPct float64 `json:"memPct" example:"45.1"`
  694. UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
  695. NetUp uint64 `json:"netUp" gorm:"column:net_up" example:"1048576"`
  696. NetDown uint64 `json:"netDown" gorm:"column:net_down" example:"2097152"`
  697. LastError string `json:"lastError"`
  698. // XrayState and XrayError are captured from the remote node's /panel/api/server/status
  699. // during heartbeats. They let the central panel distinguish "panel API reachable"
  700. // (status=online) from "Xray core itself has failed on the node" for monitoring.
  701. XrayState string `json:"xrayState" gorm:"column:xray_state"`
  702. XrayError string `json:"xrayError" gorm:"column:xray_error"`
  703. ConfigDirty bool `json:"configDirty" gorm:"default:false"`
  704. ConfigDirtyAt int64 `json:"configDirtyAt"`
  705. // InboundsAdoptedAt records the first clean traffic sync that imported the
  706. // node's pre-existing inbounds; reconcile must not sweep remote tags before it.
  707. InboundsAdoptedAt int64 `json:"-" gorm:"column:inbounds_adopted_at;default:0"`
  708. InboundCount int `json:"inboundCount" gorm:"-" example:"5"`
  709. ClientCount int `json:"clientCount" gorm:"-" example:"27"`
  710. OnlineCount int `json:"onlineCount" gorm:"-" example:"3"`
  711. ActiveCount int `json:"activeCount" gorm:"-" example:"23"`
  712. DisabledCount int `json:"disabledCount" gorm:"-" example:"3"`
  713. DepletedCount int `json:"depletedCount" gorm:"-" example:"1"`
  714. // ParentGuid + Transitive are set only when a node is surfaced as part of a
  715. // node tree (#4983): direct nodes carry the master panel's own GUID, a
  716. // transitive sub-node carries its parent node's GUID. Transitive nodes are
  717. // read-only projections (Id == 0, not persisted) — never edited or deployed.
  718. ParentGuid string `json:"parentGuid,omitempty" gorm:"-"`
  719. Transitive bool `json:"transitive,omitempty" gorm:"-"`
  720. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli" example:"1700000000"`
  721. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli" example:"1700000000"`
  722. }
  723. // NodeSummary is the read-only identity of a node as published one hop up: the
  724. // view a panel exposes about the nodes it directly manages, so a master can
  725. // surface transitive sub-nodes in a chained topology (#4983). Counts are
  726. // computed by the consuming master from its own per-GUID data, never trusted
  727. // from the child, so this carries identity/health only.
  728. type NodeSummary struct {
  729. Guid string `json:"guid"`
  730. ParentGuid string `json:"parentGuid"`
  731. Name string `json:"name"`
  732. Address string `json:"address"`
  733. Scheme string `json:"scheme"`
  734. Port int `json:"port"`
  735. Status string `json:"status"`
  736. LastHeartbeat int64 `json:"lastHeartbeat"`
  737. LatencyMs int `json:"latencyMs"`
  738. PanelVersion string `json:"panelVersion"`
  739. XrayVersion string `json:"xrayVersion"`
  740. // XrayState/XrayError forwarded so masters can surface xray failure on transitive sub-nodes too.
  741. XrayState string `json:"xrayState"`
  742. XrayError string `json:"xrayError,omitempty"`
  743. }
  744. type ClientReverse struct {
  745. Tag string `json:"tag"`
  746. }
  747. // Client represents a client configuration for Xray inbounds with traffic limits and settings.
  748. type Client struct {
  749. ID string `json:"id,omitempty"` // Unique client identifier
  750. Security string `json:"security"` // Security method (e.g., "auto", "aes-128-gcm")
  751. Password string `json:"password,omitempty"` // Client password
  752. Flow string `json:"flow,omitempty"` // Flow control (XTLS)
  753. Reverse *ClientReverse `json:"reverse,omitempty"` // VLESS simple reverse proxy settings
  754. Auth string `json:"auth,omitempty"` // Auth password (Hysteria)
  755. PrivateKey string `json:"privateKey,omitempty"`
  756. PublicKey string `json:"publicKey,omitempty"`
  757. AllowedIPs []string `json:"allowedIPs,omitempty"`
  758. PreSharedKey string `json:"preSharedKey,omitempty"`
  759. KeepAlive int `json:"keepAlive,omitempty"`
  760. Secret string `json:"secret,omitempty" example:"ee1234567890abcdef1234567890abcd7777772e636c6f7564666c6172652e636f6d"`
  761. AdTag string `json:"adTag,omitempty" example:"0123456789abcdef0123456789abcdef"`
  762. Email string `json:"email"` // Client email identifier
  763. LimitIP int `json:"limitIp"` // IP limit for this client
  764. TotalGB int64 `json:"totalGB" form:"totalGB"` // Total traffic limit in GB
  765. ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` // Expiration timestamp
  766. Enable bool `json:"enable" form:"enable"` // Whether the client is enabled
  767. TgID int64 `json:"tgId" form:"tgId"` // Telegram user ID for notifications
  768. SubID string `json:"subId" form:"subId"` // Subscription identifier
  769. Group string `json:"group,omitempty" form:"group"` // Logical grouping label
  770. Comment string `json:"comment" form:"comment"` // Client comment
  771. Reset int `json:"reset" form:"reset"` // Reset period in days
  772. CreatedAt int64 `json:"created_at,omitempty"` // Creation timestamp
  773. UpdatedAt int64 `json:"updated_at,omitempty"` // Last update timestamp
  774. }
  775. type ClientRecord struct {
  776. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  777. Email string `json:"email" gorm:"uniqueIndex;not null"`
  778. SubID string `json:"subId" gorm:"index;column:sub_id"`
  779. UUID string `json:"uuid" gorm:"column:uuid"`
  780. Password string `json:"password"`
  781. Auth string `json:"auth"`
  782. Flow string `json:"flow"`
  783. Security string `json:"security"`
  784. Reverse string `json:"reverse" gorm:"column:reverse"`
  785. PrivateKey string `json:"privateKey" gorm:"column:wg_private_key"`
  786. PublicKey string `json:"publicKey" gorm:"column:wg_public_key"`
  787. AllowedIPs string `json:"allowedIPs" gorm:"column:wg_allowed_ips"`
  788. PreSharedKey string `json:"preSharedKey" gorm:"column:wg_pre_shared_key"`
  789. KeepAlive int `json:"keepAlive" gorm:"column:wg_keep_alive;default:0"`
  790. Secret string `json:"secret" gorm:"column:secret"`
  791. AdTag string `json:"adTag" gorm:"column:ad_tag;default:''"`
  792. LimitIP int `json:"limitIp" gorm:"column:limit_ip"`
  793. TotalGB int64 `json:"totalGB" gorm:"column:total_gb"`
  794. ExpiryTime int64 `json:"expiryTime" gorm:"column:expiry_time"`
  795. Enable bool `json:"enable" gorm:"default:true"`
  796. TgID int64 `json:"tgId" gorm:"column:tg_id"`
  797. Group string `json:"group" gorm:"column:group_name;default:'';index:idx_client_record_group"`
  798. Comment string `json:"comment"`
  799. Reset int `json:"reset" gorm:"default:0"`
  800. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  801. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  802. }
  803. func (ClientRecord) TableName() string { return "clients" }
  804. type ClientGroup struct {
  805. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  806. Name string `json:"name" gorm:"uniqueIndex;not null"`
  807. ResetUp int64 `json:"resetUp" gorm:"column:reset_up;default:0"`
  808. ResetDown int64 `json:"resetDown" gorm:"column:reset_down;default:0"`
  809. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  810. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  811. }
  812. func (ClientGroup) TableName() string { return "client_groups" }
  813. // MarshalJSON emits the reverse column as a nested JSON object rather than an
  814. // escaped JSON-text string, matching the same convention Inbound uses for its
  815. // JSON-text columns. Empty storage renders as null.
  816. func (r ClientRecord) MarshalJSON() ([]byte, error) {
  817. type alias ClientRecord
  818. return json.Marshal(struct {
  819. alias
  820. Reverse json.RawMessage `json:"reverse"`
  821. }{
  822. alias: alias(r),
  823. Reverse: jsonStringFieldToRaw(r.Reverse),
  824. })
  825. }
  826. // UnmarshalJSON accepts reverse as either a JSON object (modern shape) or a
  827. // JSON-encoded string (legacy shape).
  828. func (r *ClientRecord) UnmarshalJSON(data []byte) error {
  829. type alias ClientRecord
  830. aux := struct {
  831. *alias
  832. Reverse json.RawMessage `json:"reverse"`
  833. }{
  834. alias: (*alias)(r),
  835. }
  836. if err := json.Unmarshal(data, &aux); err != nil {
  837. return err
  838. }
  839. r.Reverse = jsonStringFieldFromRaw(aux.Reverse)
  840. return nil
  841. }
  842. type ClientInbound struct {
  843. ClientId int `json:"clientId" gorm:"primaryKey;column:client_id;index"`
  844. InboundId int `json:"inboundId" gorm:"primaryKey;column:inbound_id;index"`
  845. FlowOverride string `json:"flowOverride" gorm:"column:flow_override"`
  846. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  847. }
  848. func (ClientInbound) TableName() string { return "client_inbounds" }
  849. // ClientExternalLink is a per-client entry surfaced in the client's
  850. // subscription. Two kinds:
  851. // - "link": a single third-party share link (vless://, vmess://, trojan://,
  852. // ss://, hysteria2://, wireguard://). Emitted verbatim in raw subs; parsed
  853. // into an outbound/proxy for JSON and Clash.
  854. // - "subscription": a remote subscription URL. The panel fetches it (cached),
  855. // decodes its links, and merges them into the client's subscription.
  856. type ClientExternalLink struct {
  857. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  858. ClientId int `json:"clientId" gorm:"index;column:client_id"`
  859. Kind string `json:"kind" gorm:"column:kind"`
  860. Value string `json:"value" gorm:"column:value"`
  861. Remark string `json:"remark" gorm:"column:remark"`
  862. SortIndex int `json:"sortIndex" gorm:"column:sort_index"`
  863. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  864. }
  865. func (ClientExternalLink) TableName() string { return "client_external_links" }
  866. // External link kinds.
  867. const (
  868. ExternalLinkKindLink = "link"
  869. ExternalLinkKindSubscription = "subscription"
  870. )
  871. type InboundFallback struct {
  872. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  873. MasterId int `json:"masterId" gorm:"index;not null;column:master_id"`
  874. ChildId int `json:"childId" gorm:"index;not null;column:child_id"`
  875. Name string `json:"name"`
  876. Alpn string `json:"alpn"`
  877. Path string `json:"path"`
  878. Dest string `json:"dest"`
  879. Xver int `json:"xver"`
  880. SortOrder int `json:"sortOrder" gorm:"default:0;column:sort_order"`
  881. }
  882. func (InboundFallback) TableName() string { return "inbound_fallbacks" }
  883. type Host struct {
  884. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement" example:"1"`
  885. GroupId string `json:"groupId" form:"groupId" gorm:"column:group_id;index"`
  886. InboundId int `json:"inboundId" form:"inboundId" gorm:"index;not null;column:inbound_id" validate:"required" example:"1"`
  887. SortOrder int `json:"sortOrder" form:"sortOrder" gorm:"default:0;column:sort_order"`
  888. Remark string `json:"remark" form:"remark" validate:"required,max=256" example:"cdn-front"`
  889. ServerDescription string `json:"serverDescription" form:"serverDescription" gorm:"column:server_description" validate:"omitempty,max=64"`
  890. IsDisabled bool `json:"isDisabled" form:"isDisabled" gorm:"default:false;column:is_disabled"`
  891. IsHidden bool `json:"isHidden" form:"isHidden" gorm:"default:false;column:is_hidden"`
  892. Tags []string `json:"tags" form:"tags" gorm:"serializer:json"`
  893. Address string `json:"address" form:"address" example:"cdn.example.com"`
  894. Port int `json:"port" form:"port" gorm:"default:0" validate:"gte=0,lte=65535" example:"8443"`
  895. Security string `json:"security" form:"security" gorm:"default:same" validate:"omitempty,oneof=same tls none reality" example:"same"`
  896. Sni string `json:"sni" form:"sni"`
  897. HostHeader string `json:"hostHeader" form:"hostHeader" gorm:"column:host_header"`
  898. Path string `json:"path" form:"path"`
  899. Alpn []string `json:"alpn" form:"alpn" gorm:"serializer:json"`
  900. Fingerprint string `json:"fingerprint" form:"fingerprint"`
  901. OverrideSniFromAddress bool `json:"overrideSniFromAddress" form:"overrideSniFromAddress" gorm:"column:override_sni_from_address"`
  902. KeepSniBlank bool `json:"keepSniBlank" form:"keepSniBlank" gorm:"column:keep_sni_blank"`
  903. PinnedPeerCertSha256 []string `json:"pinnedPeerCertSha256" form:"pinnedPeerCertSha256" gorm:"serializer:json;column:pinned_peer_cert_sha256"`
  904. VerifyPeerCertByName string `json:"verifyPeerCertByName" form:"verifyPeerCertByName" gorm:"column:verify_peer_cert_by_name"`
  905. AllowInsecure bool `json:"allowInsecure" form:"allowInsecure" gorm:"column:allow_insecure"`
  906. EchConfigList string `json:"echConfigList" form:"echConfigList" gorm:"column:ech_config_list"`
  907. MuxParams string `json:"muxParams" form:"muxParams" gorm:"type:text;column:mux_params"`
  908. SockoptParams string `json:"sockoptParams" form:"sockoptParams" gorm:"type:text;column:sockopt_params"`
  909. // FinalMask is a JSON object of xray finalmask masks (tcp/udp/quicParams),
  910. // merged into this host's JSON-subscription stream. Empty = no override.
  911. FinalMask string `json:"finalMask" form:"finalMask" gorm:"type:text;column:final_mask"`
  912. // Single VLESS route value (0-65535) baked into the subscription UUID's 3rd
  913. // group (bytes 6-7), which xray reads via net.PortFromBytes(id[6:8]). Empty = none.
  914. VlessRoute string `json:"vlessRoute" form:"vlessRoute" gorm:"column:vless_route" example:"443"`
  915. ExcludeFromSubTypes []string `json:"excludeFromSubTypes" form:"excludeFromSubTypes" gorm:"serializer:json;column:exclude_from_sub_types"`
  916. MihomoIpVersion string `json:"mihomoIpVersion" form:"mihomoIpVersion" gorm:"column:mihomo_ip_version" validate:"omitempty,oneof=dual ipv4 ipv6 ipv4-prefer ipv6-prefer"`
  917. MihomoX25519 bool `json:"mihomoX25519" form:"mihomoX25519" gorm:"column:mihomo_x25519"`
  918. ShuffleHost bool `json:"shuffleHost" form:"shuffleHost" gorm:"column:shuffle_host"`
  919. NodeGuids []string `json:"nodeGuids,omitempty" form:"nodeGuids" gorm:"serializer:json;column:node_guids"`
  920. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  921. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  922. }
  923. func (Host) TableName() string { return "hosts" }
  924. func (c *Client) ToRecord() *ClientRecord {
  925. rec := &ClientRecord{
  926. Email: c.Email,
  927. SubID: c.SubID,
  928. UUID: c.ID,
  929. Password: c.Password,
  930. Auth: c.Auth,
  931. Flow: c.Flow,
  932. Security: c.Security,
  933. LimitIP: c.LimitIP,
  934. TotalGB: c.TotalGB,
  935. ExpiryTime: c.ExpiryTime,
  936. Enable: c.Enable,
  937. TgID: c.TgID,
  938. Group: c.Group,
  939. Comment: c.Comment,
  940. Reset: c.Reset,
  941. CreatedAt: c.CreatedAt,
  942. UpdatedAt: c.UpdatedAt,
  943. PrivateKey: c.PrivateKey,
  944. PublicKey: c.PublicKey,
  945. AllowedIPs: strings.Join(c.AllowedIPs, ","),
  946. PreSharedKey: c.PreSharedKey,
  947. KeepAlive: c.KeepAlive,
  948. Secret: c.Secret,
  949. AdTag: c.AdTag,
  950. }
  951. if c.Reverse != nil {
  952. if b, err := json.Marshal(c.Reverse); err == nil {
  953. rec.Reverse = string(b)
  954. }
  955. }
  956. return rec
  957. }
  958. func splitWireguardAllowedIPs(csv string) []string {
  959. if csv == "" {
  960. return nil
  961. }
  962. parts := strings.Split(csv, ",")
  963. out := make([]string, 0, len(parts))
  964. for _, p := range parts {
  965. if trimmed := strings.TrimSpace(p); trimmed != "" {
  966. out = append(out, trimmed)
  967. }
  968. }
  969. if len(out) == 0 {
  970. return nil
  971. }
  972. return out
  973. }
  974. func (r *ClientRecord) ToClient() *Client {
  975. c := &Client{
  976. ID: r.UUID,
  977. Email: r.Email,
  978. SubID: r.SubID,
  979. Password: r.Password,
  980. Auth: r.Auth,
  981. Flow: r.Flow,
  982. Security: r.Security,
  983. LimitIP: r.LimitIP,
  984. TotalGB: r.TotalGB,
  985. ExpiryTime: r.ExpiryTime,
  986. Enable: r.Enable,
  987. TgID: r.TgID,
  988. Group: r.Group,
  989. Comment: r.Comment,
  990. Reset: r.Reset,
  991. CreatedAt: r.CreatedAt,
  992. UpdatedAt: r.UpdatedAt,
  993. PrivateKey: r.PrivateKey,
  994. PublicKey: r.PublicKey,
  995. AllowedIPs: splitWireguardAllowedIPs(r.AllowedIPs),
  996. PreSharedKey: r.PreSharedKey,
  997. KeepAlive: r.KeepAlive,
  998. Secret: r.Secret,
  999. AdTag: r.AdTag,
  1000. }
  1001. if r.Reverse != "" {
  1002. var rev ClientReverse
  1003. if err := json.Unmarshal([]byte(r.Reverse), &rev); err == nil {
  1004. c.Reverse = &rev
  1005. }
  1006. }
  1007. return c
  1008. }
  1009. type ClientMergeConflict struct {
  1010. Field string
  1011. Old any
  1012. New any
  1013. Kept any
  1014. }
  1015. type OutboundSubscription struct {
  1016. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
  1017. Remark string `json:"remark" form:"remark"`
  1018. Url string `json:"url" form:"url"`
  1019. Enabled bool `json:"enabled" form:"enabled" gorm:"default:true"`
  1020. AllowPrivate bool `json:"allowPrivate" form:"allowPrivate" gorm:"default:false"`
  1021. TagPrefix string `json:"tagPrefix" form:"tagPrefix"`
  1022. UpdateInterval int `json:"updateInterval" form:"updateInterval" gorm:"default:600"` // seconds between refreshes
  1023. Priority int `json:"priority" form:"priority" gorm:"default:0"` // order among subscriptions in the merged outbounds (lower = earlier)
  1024. Prepend bool `json:"prepend" form:"prepend" gorm:"default:false"` // place this subscription's outbounds before the manual template outbounds
  1025. LastUpdated int64 `json:"lastUpdated" form:"lastUpdated"`
  1026. LastError string `json:"lastError" form:"lastError"`
  1027. LastFetchedOutbounds string `json:"lastFetchedOutbounds" form:"lastFetchedOutbounds" gorm:"type:text"`
  1028. LinkIdentities string `json:"-" gorm:"type:text;column:link_identities"`
  1029. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  1030. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  1031. OutboundCount int `json:"outboundCount" gorm:"-"`
  1032. }
  1033. func MergeClientRecord(existing *ClientRecord, incoming *ClientRecord) []ClientMergeConflict {
  1034. var conflicts []ClientMergeConflict
  1035. keep := func(field string, oldV, newV, kept any) {
  1036. conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: oldV, New: newV, Kept: kept})
  1037. }
  1038. const redacted = "<redacted>"
  1039. keepSecret := func(field string) {
  1040. conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: redacted, New: redacted, Kept: redacted})
  1041. }
  1042. incomingNewer := incoming.UpdatedAt > existing.UpdatedAt ||
  1043. (incoming.UpdatedAt == existing.UpdatedAt && incoming.CreatedAt > existing.CreatedAt)
  1044. if existing.UUID != incoming.UUID && incoming.UUID != "" {
  1045. if incomingNewer || existing.UUID == "" {
  1046. existing.UUID = incoming.UUID
  1047. }
  1048. keepSecret("uuid")
  1049. }
  1050. if existing.Password != incoming.Password && incoming.Password != "" {
  1051. if incomingNewer || existing.Password == "" {
  1052. existing.Password = incoming.Password
  1053. keepSecret("password")
  1054. }
  1055. }
  1056. if existing.Auth != incoming.Auth && incoming.Auth != "" {
  1057. if incomingNewer || existing.Auth == "" {
  1058. existing.Auth = incoming.Auth
  1059. keepSecret("auth")
  1060. }
  1061. }
  1062. if existing.Flow != incoming.Flow && incoming.Flow != "" {
  1063. if incomingNewer || existing.Flow == "" {
  1064. keep("flow", existing.Flow, incoming.Flow, incoming.Flow)
  1065. existing.Flow = incoming.Flow
  1066. }
  1067. }
  1068. if existing.Security != incoming.Security && incoming.Security != "" {
  1069. if incomingNewer || existing.Security == "" {
  1070. keep("security", existing.Security, incoming.Security, incoming.Security)
  1071. existing.Security = incoming.Security
  1072. }
  1073. }
  1074. if existing.SubID != incoming.SubID && incoming.SubID != "" {
  1075. if incomingNewer || existing.SubID == "" {
  1076. existing.SubID = incoming.SubID
  1077. keepSecret("subId")
  1078. }
  1079. }
  1080. if existing.TotalGB != incoming.TotalGB {
  1081. picked := existing.TotalGB
  1082. if existing.TotalGB == 0 || (incoming.TotalGB != 0 && incoming.TotalGB > existing.TotalGB) {
  1083. picked = incoming.TotalGB
  1084. }
  1085. if picked != existing.TotalGB {
  1086. keep("totalGB", existing.TotalGB, incoming.TotalGB, picked)
  1087. existing.TotalGB = picked
  1088. }
  1089. }
  1090. if existing.ExpiryTime != incoming.ExpiryTime {
  1091. picked := existing.ExpiryTime
  1092. if existing.ExpiryTime == 0 || (incoming.ExpiryTime != 0 && incoming.ExpiryTime > existing.ExpiryTime) {
  1093. picked = incoming.ExpiryTime
  1094. }
  1095. if picked != existing.ExpiryTime {
  1096. keep("expiryTime", existing.ExpiryTime, incoming.ExpiryTime, picked)
  1097. existing.ExpiryTime = picked
  1098. }
  1099. }
  1100. if existing.LimitIP != incoming.LimitIP && incoming.LimitIP != 0 {
  1101. picked := existing.LimitIP
  1102. if existing.LimitIP == 0 || incoming.LimitIP > existing.LimitIP {
  1103. picked = incoming.LimitIP
  1104. }
  1105. if picked != existing.LimitIP {
  1106. keep("limitIp", existing.LimitIP, incoming.LimitIP, picked)
  1107. existing.LimitIP = picked
  1108. }
  1109. }
  1110. if existing.TgID != incoming.TgID && incoming.TgID != 0 {
  1111. if incomingNewer || existing.TgID == 0 {
  1112. keep("tgId", existing.TgID, incoming.TgID, incoming.TgID)
  1113. existing.TgID = incoming.TgID
  1114. }
  1115. }
  1116. if existing.Reset != incoming.Reset && incoming.Reset != 0 {
  1117. if incomingNewer || existing.Reset == 0 {
  1118. keep("reset", existing.Reset, incoming.Reset, incoming.Reset)
  1119. existing.Reset = incoming.Reset
  1120. }
  1121. }
  1122. if existing.Reverse != incoming.Reverse && incoming.Reverse != "" {
  1123. if incomingNewer || existing.Reverse == "" {
  1124. keep("reverse", existing.Reverse, incoming.Reverse, incoming.Reverse)
  1125. existing.Reverse = incoming.Reverse
  1126. }
  1127. }
  1128. if existing.PrivateKey != incoming.PrivateKey && incoming.PrivateKey != "" {
  1129. if incomingNewer || existing.PrivateKey == "" {
  1130. existing.PrivateKey = incoming.PrivateKey
  1131. keepSecret("privateKey")
  1132. }
  1133. }
  1134. if existing.PublicKey != incoming.PublicKey && incoming.PublicKey != "" {
  1135. if incomingNewer || existing.PublicKey == "" {
  1136. existing.PublicKey = incoming.PublicKey
  1137. keepSecret("publicKey")
  1138. }
  1139. }
  1140. if existing.PreSharedKey != incoming.PreSharedKey && incoming.PreSharedKey != "" {
  1141. if incomingNewer || existing.PreSharedKey == "" {
  1142. existing.PreSharedKey = incoming.PreSharedKey
  1143. keepSecret("preSharedKey")
  1144. }
  1145. }
  1146. if existing.Secret != incoming.Secret && incoming.Secret != "" {
  1147. if incomingNewer || existing.Secret == "" {
  1148. existing.Secret = incoming.Secret
  1149. keepSecret("secret")
  1150. }
  1151. }
  1152. if existing.AllowedIPs != incoming.AllowedIPs && incoming.AllowedIPs != "" {
  1153. if incomingNewer || existing.AllowedIPs == "" {
  1154. keep("allowedIPs", existing.AllowedIPs, incoming.AllowedIPs, incoming.AllowedIPs)
  1155. existing.AllowedIPs = incoming.AllowedIPs
  1156. }
  1157. }
  1158. if existing.KeepAlive != incoming.KeepAlive && incoming.KeepAlive != 0 {
  1159. if incomingNewer || existing.KeepAlive == 0 {
  1160. keep("keepAlive", existing.KeepAlive, incoming.KeepAlive, incoming.KeepAlive)
  1161. existing.KeepAlive = incoming.KeepAlive
  1162. }
  1163. }
  1164. if existing.Comment != incoming.Comment && incoming.Comment != "" {
  1165. if incomingNewer || existing.Comment == "" {
  1166. keep("comment", existing.Comment, incoming.Comment, incoming.Comment)
  1167. existing.Comment = incoming.Comment
  1168. }
  1169. }
  1170. if existing.Group != incoming.Group && incoming.Group != "" {
  1171. if incomingNewer || existing.Group == "" {
  1172. keep("group", existing.Group, incoming.Group, incoming.Group)
  1173. existing.Group = incoming.Group
  1174. }
  1175. }
  1176. if existing.Enable != incoming.Enable {
  1177. if incoming.Enable {
  1178. if !existing.Enable {
  1179. keep("enable", existing.Enable, incoming.Enable, true)
  1180. existing.Enable = true
  1181. }
  1182. }
  1183. }
  1184. if incoming.CreatedAt != 0 && (existing.CreatedAt == 0 || incoming.CreatedAt < existing.CreatedAt) {
  1185. existing.CreatedAt = incoming.CreatedAt
  1186. }
  1187. if incoming.UpdatedAt > existing.UpdatedAt {
  1188. existing.UpdatedAt = incoming.UpdatedAt
  1189. }
  1190. return conflicts
  1191. }