1
0

model.go 54 KB

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