1
0

model.go 53 KB

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