client_crud.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. package service
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/netip"
  8. "runtime/debug"
  9. "slices"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. "unicode"
  15. "github.com/google/uuid"
  16. "github.com/mhsanaei/3x-ui/v3/internal/database"
  17. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  18. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  19. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  20. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  21. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  22. "gorm.io/gorm"
  23. )
  24. func hasForbiddenClientChar(s string) bool {
  25. for _, r := range s {
  26. if r == '/' || r == '\\' || r < 0x20 || r == 0x7f || unicode.IsSpace(r) {
  27. return true
  28. }
  29. }
  30. return false
  31. }
  32. func validateClientEmail(email string) error {
  33. if hasForbiddenClientChar(email) {
  34. return common.NewError("client email contains an invalid character:", email)
  35. }
  36. return nil
  37. }
  38. func validateClientSubID(subID string) error {
  39. if hasForbiddenClientChar(subID) {
  40. return common.NewError("client subId contains an invalid character:", subID)
  41. }
  42. return nil
  43. }
  44. // Rejected rather than coerced: an unknown cycle would leave the operator with
  45. // a field that reads as configured while no job ever selects the client.
  46. func validateClientTrafficReset(period string, day int) error {
  47. switch period {
  48. case "", "never", "hourly", "daily", "weekly", "monthly":
  49. default:
  50. return common.NewError("client trafficReset must be never, hourly, daily, weekly or monthly, got:", period)
  51. }
  52. if day < 0 || day > 31 {
  53. return common.NewError("client trafficResetDay must be between 0 and 31, got:", day)
  54. }
  55. return nil
  56. }
  57. // Rejected rather than clamped: nextCalendarRenewal would silently move an
  58. // out-of-range day, and a negative one drops out of the renewal query entirely.
  59. func validateClientResetDay(day int) error {
  60. if day < 0 || day > 31 {
  61. return common.NewError("client resetDay must be between 0 and 31, got:", day)
  62. }
  63. return nil
  64. }
  65. // Rejected rather than coerced: a negative cap reads as "unlimited" to a caller
  66. // but selects nothing, so the client would silently stop renewing.
  67. func validateClientResetMax(resetMax int) error {
  68. if resetMax < 0 {
  69. return common.NewError("client resetMax must not be negative, got:", resetMax)
  70. }
  71. return nil
  72. }
  73. // normalizeClientTrafficReset stores what the inbound path would store, so the
  74. // day never reaches the DB as a 0 that three layers downstream each clamp to 1.
  75. func normalizeClientTrafficReset(c *model.Client) {
  76. if c.TrafficReset == "" {
  77. c.TrafficReset = "never"
  78. }
  79. c.TrafficResetDay = normalizeTrafficResetDay(c.TrafficResetDay)
  80. }
  81. // ClientResetCycle is the slice of a client the reset job needs: enough to know
  82. // whether it is due, and whether its disable is the quota's doing or the operator's.
  83. type ClientResetCycle struct {
  84. Email string
  85. TrafficResetDay int
  86. Enable bool
  87. Total int64
  88. Used int64
  89. }
  90. // Depleted reports a client the quota switched off. A reset restores that one;
  91. // a client disabled below its quota was switched off by hand and stays off.
  92. func (c ClientResetCycle) Depleted() bool {
  93. return c.Total > 0 && c.Used >= c.Total
  94. }
  95. // GetClientsByTrafficReset returns the clients whose own reset cycle matches the
  96. // period, independent of the cycle configured on the inbounds they belong to.
  97. func (s *ClientService) GetClientsByTrafficReset(period string) ([]ClientResetCycle, error) {
  98. var cycles []ClientResetCycle
  99. err := database.GetDB().Table("clients c").
  100. Select("c.email, c.traffic_reset_day, c.enable, COALESCE(ct.total, 0) AS total, COALESCE(ct.up, 0) + COALESCE(ct.down, 0) AS used").
  101. Joins("LEFT JOIN client_traffics ct ON ct.email = c.email").
  102. Where("c.traffic_reset = ?", period).
  103. Scan(&cycles).Error
  104. if err != nil {
  105. return nil, err
  106. }
  107. return cycles, nil
  108. }
  109. // Create applies the client to every requested inbound: one failing inbound no
  110. // longer aborts the others, so the error can name several and needRestart holds.
  111. func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) {
  112. if payload == nil {
  113. return false, common.NewError("empty payload")
  114. }
  115. client := payload.Client
  116. if strings.TrimSpace(client.Email) == "" {
  117. return false, common.NewError("client email is required")
  118. }
  119. if err := validateClientEmail(client.Email); err != nil {
  120. return false, err
  121. }
  122. if err := validateClientSubID(client.SubID); err != nil {
  123. return false, err
  124. }
  125. if err := validateClientResetDay(client.ResetDay); err != nil {
  126. return false, err
  127. }
  128. if err := validateClientResetMax(client.ResetMax); err != nil {
  129. return false, err
  130. }
  131. if err := validateClientTrafficReset(client.TrafficReset, client.TrafficResetDay); err != nil {
  132. return false, err
  133. }
  134. normalizeClientTrafficReset(&client)
  135. if len(payload.InboundIds) == 0 {
  136. return false, common.NewError("at least one inbound is required")
  137. }
  138. if client.SubID == "" {
  139. client.SubID = uuid.NewString()
  140. }
  141. if !client.Enable {
  142. client.Enable = true
  143. }
  144. now := time.Now().UnixMilli()
  145. if client.CreatedAt == 0 {
  146. client.CreatedAt = now
  147. }
  148. client.UpdatedAt = now
  149. existing := &model.ClientRecord{}
  150. err := database.GetDB().Where("email = ?", client.Email).First(existing).Error
  151. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  152. return false, err
  153. }
  154. emailTaken := !errors.Is(err, gorm.ErrRecordNotFound)
  155. if emailTaken {
  156. if existing.SubID == "" || existing.SubID != client.SubID {
  157. return false, common.NewError("email already in use:", client.Email)
  158. }
  159. // Reuse stored credentials when re-adding an existing identity, or
  160. // fillProtocolDefaults mints a fresh UUID that desyncs other inbounds.
  161. if client.ID == "" {
  162. client.ID = existing.UUID
  163. }
  164. if client.Password == "" {
  165. client.Password = existing.Password
  166. }
  167. if client.Auth == "" {
  168. client.Auth = existing.Auth
  169. }
  170. if client.Secret == "" {
  171. client.Secret = existing.Secret
  172. }
  173. }
  174. if client.SubID != "" {
  175. var subTaken int64
  176. if err := database.GetDB().Model(&model.ClientRecord{}).
  177. Where("sub_id = ? AND email <> ?", client.SubID, client.Email).
  178. Count(&subTaken).Error; err != nil {
  179. return false, err
  180. }
  181. if subTaken > 0 {
  182. return false, common.NewError("subId already in use:", client.SubID)
  183. }
  184. }
  185. // Prepared before any inbound is written: fillProtocolDefaults mints the
  186. // shared credentials on the first inbound and every later one reuses them.
  187. adds := make([]*model.Inbound, 0, len(payload.InboundIds))
  188. for _, ibId := range payload.InboundIds {
  189. inbound, getErr := inboundSvc.GetInbound(ibId)
  190. if getErr != nil {
  191. return false, fmt.Errorf("inbound %d: %w", ibId, getErr)
  192. }
  193. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  194. return false, fmt.Errorf("inbound %d: %w", ibId, err)
  195. }
  196. clientForInbound := client
  197. if ips, ok := client.AllowedIPsByInbound[ibId]; ok {
  198. clientForInbound.AllowedIPs = ips
  199. } else if !addressesFitAmneziaWGInbound(clientForInbound.AllowedIPs, inbound) {
  200. // The shared AllowedIPs value (e.g. from a single-field legacy
  201. // caller) came from a different subnet than this inbound's own --
  202. // clear it so defaultAmneziaWGClients allocates a fresh, correct
  203. // address for THIS inbound instead of persisting an unroutable
  204. // peer. Same reasoning as addressesFitAmneziaWGInbound's own doc
  205. // comment on the Attach path.
  206. clientForInbound.AllowedIPs = nil
  207. }
  208. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(clientForInbound, inbound)}})
  209. if mErr != nil {
  210. return false, fmt.Errorf("inbound %d: %w", ibId, mErr)
  211. }
  212. adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload)})
  213. }
  214. needRestart, fanoutErr := s.fanoutInboundClientAdds(inboundSvc, adds)
  215. if fanoutErr != nil {
  216. // Never on a failed create: this retrims the devices of an email that
  217. // already existed, and a create the panel reported as failed must not.
  218. return needRestart, fanoutErr
  219. }
  220. return needRestart, s.setClientLimitHwidByEmail(nil, client.Email, payload.LimitHwid)
  221. }
  222. // inboundFanoutConcurrency caps how many inbounds one client op applies at
  223. // once, so a client spanning many of them can't start an unbounded RPC burst.
  224. const inboundFanoutConcurrency = 4
  225. // inboundApply is one inbound's share of a client op, ready to run.
  226. type inboundApply struct {
  227. id int
  228. run func() (bool, error)
  229. }
  230. // fanoutInboundApplies runs the applies with the node pushes overlapping, so a
  231. // client spanning several nodes no longer costs one RPC round-trip per node.
  232. func fanoutInboundApplies(applies []inboundApply) (bool, error) {
  233. var needRestart atomic.Bool
  234. errs := make([]error, len(applies))
  235. sem := make(chan struct{}, inboundFanoutConcurrency)
  236. var wg sync.WaitGroup
  237. for i := range applies {
  238. wg.Add(1)
  239. sem <- struct{}{}
  240. go func() {
  241. defer wg.Done()
  242. defer func() { <-sem }()
  243. // Off the request goroutine gin's Recovery no longer covers this,
  244. // so an unrecovered panic here would take the whole panel down.
  245. defer func() {
  246. if r := recover(); r != nil {
  247. // The apply may already have committed, so ask for the
  248. // restart the lost return value can no longer report.
  249. needRestart.Store(true)
  250. errs[i] = fmt.Errorf("inbound %d: panic: %v", applies[i].id, r)
  251. logger.Errorf("panic applying client change to inbound %d: %v\n%s", applies[i].id, r, debug.Stack())
  252. }
  253. }()
  254. nr, err := applies[i].run()
  255. if nr {
  256. needRestart.Store(true)
  257. }
  258. if err != nil {
  259. errs[i] = fmt.Errorf("inbound %d: %w", applies[i].id, err)
  260. }
  261. }()
  262. }
  263. wg.Wait()
  264. return needRestart.Load(), errors.Join(errs...)
  265. }
  266. // fanoutInboundClientAdds applies one payload per inbound.
  267. func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound) (bool, error) {
  268. applies := make([]inboundApply, 0, len(adds))
  269. for _, add := range adds {
  270. applies = append(applies, inboundApply{id: add.Id, run: func() (bool, error) {
  271. return s.AddInboundClient(inboundSvc, add)
  272. }})
  273. }
  274. return fanoutInboundApplies(applies)
  275. }
  276. // fanoutInboundResults runs one job per inbound with the node pushes
  277. // overlapping, so a bulk op costs one RPC round-trip instead of one per node.
  278. // limit is the caller's own cap: an op that allocates tunnel addresses passes 1,
  279. // because allocation reads a cross-inbound used-set before it writes.
  280. func fanoutInboundResults[T any](inboundIds []int, limit int, run func(i int) T) ([]T, []error) {
  281. if limit < 1 {
  282. limit = 1
  283. }
  284. out := make([]T, len(inboundIds))
  285. errs := make([]error, len(inboundIds))
  286. sem := make(chan struct{}, limit)
  287. var wg sync.WaitGroup
  288. for i := range inboundIds {
  289. wg.Add(1)
  290. sem <- struct{}{}
  291. go func() {
  292. defer wg.Done()
  293. defer func() { <-sem }()
  294. // Off the request goroutine gin's Recovery no longer covers this,
  295. // so an unrecovered panic here would take the whole panel down.
  296. defer func() {
  297. if r := recover(); r != nil {
  298. errs[i] = fmt.Errorf("inbound %d: panic: %v", inboundIds[i], r)
  299. logger.Errorf("panic applying bulk client change to inbound %d: %v\n%s", inboundIds[i], r, debug.Stack())
  300. }
  301. }()
  302. out[i] = run(i)
  303. }()
  304. }
  305. wg.Wait()
  306. return out, errs
  307. }
  308. // addFanoutLimit serializes an add that touches a tunnel inbound. WireGuard and
  309. // AmneziaWG pick a free peer address by reading every inbound's used-set first,
  310. // so two overlapping allocations hand out the same one and the second is refused.
  311. func addFanoutLimit(anyTunnel bool) int {
  312. if anyTunnel {
  313. return 1
  314. }
  315. return inboundFanoutConcurrency
  316. }
  317. // sortedInboundIds gives the fanout a stable order, so which inbound wins a
  318. // per-email report no longer depends on Go's map iteration order.
  319. func sortedInboundIds[V any](byInbound map[int]V) []int {
  320. ids := make([]int, 0, len(byInbound))
  321. for id := range byInbound {
  322. ids = append(ids, id)
  323. }
  324. slices.Sort(ids)
  325. return ids
  326. }
  327. // markInboundNodesDirty makes a half-applied client edit unobservable to a node
  328. // snapshot merge, which skips a node whose config is already flagged dirty.
  329. func markInboundNodesDirty(inboundIds []int) error {
  330. if len(inboundIds) == 0 {
  331. return nil
  332. }
  333. var nodeIDs []int
  334. for _, batch := range chunkInts(inboundIds, sqlInChunk) {
  335. var ids []int
  336. if err := database.GetDB().Model(&model.Inbound{}).
  337. Where("id IN ? AND node_id IS NOT NULL", batch).
  338. Distinct().Pluck("node_id", &ids).Error; err != nil {
  339. return err
  340. }
  341. nodeIDs = append(nodeIDs, ids...)
  342. }
  343. if len(nodeIDs) == 0 {
  344. return nil
  345. }
  346. return runSerializedTx(func(tx *gorm.DB) error {
  347. svc := &NodeService{}
  348. for _, id := range nodeIDs {
  349. if err := svc.MarkNodeDirtyTx(tx, id); err != nil {
  350. return err
  351. }
  352. }
  353. return nil
  354. })
  355. }
  356. func (s *ClientService) fillProtocolDefaults(c *model.Client, ib *model.Inbound) error {
  357. switch ib.Protocol {
  358. case model.VMESS, model.VLESS:
  359. if c.ID == "" {
  360. c.ID = uuid.NewString()
  361. }
  362. case model.Trojan:
  363. if c.Password == "" {
  364. c.Password = strings.ReplaceAll(uuid.NewString(), "-", "")
  365. }
  366. case model.Shadowsocks:
  367. method := shadowsocksMethodFromSettings(ib.Settings)
  368. if c.Password == "" || !validShadowsocksClientKey(method, c.Password) {
  369. c.Password = randomShadowsocksClientKey(method)
  370. }
  371. case model.Hysteria:
  372. if c.Auth == "" {
  373. c.Auth = strings.ReplaceAll(uuid.NewString(), "-", "")
  374. }
  375. case model.MTProto:
  376. if c.Secret == "" {
  377. c.Secret = model.GenerateFakeTLSSecret(mtprotoDomainFromSettings(ib.Settings))
  378. }
  379. }
  380. return nil
  381. }
  382. // defaultMtprotoDomain is the FakeTLS fronting domain used when an mtproto
  383. // inbound carries no fakeTlsDomain of its own; it mirrors the frontend default.
  384. const defaultMtprotoDomain = "www.cloudflare.com"
  385. // mtprotoDomainFromSettings returns the inbound-level FakeTLS domain, falling
  386. // back to the default when unset, so a generated client secret always fronts a
  387. // real hostname.
  388. func mtprotoDomainFromSettings(settings string) string {
  389. domain := ""
  390. if settings != "" {
  391. var m map[string]any
  392. if err := json.Unmarshal([]byte(settings), &m); err == nil {
  393. domain, _ = m["fakeTlsDomain"].(string)
  394. }
  395. }
  396. domain = strings.TrimSpace(domain)
  397. if domain == "" {
  398. return defaultMtprotoDomain
  399. }
  400. return domain
  401. }
  402. func clientWithInboundFlow(c model.Client, ib *model.Inbound) model.Client {
  403. if ib.DisableFlow || !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings) {
  404. c.Flow = ""
  405. }
  406. return c
  407. }
  408. func shadowsocksMethodFromSettings(settings string) string {
  409. if settings == "" {
  410. return ""
  411. }
  412. var m map[string]any
  413. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  414. return ""
  415. }
  416. method, _ := m["method"].(string)
  417. return method
  418. }
  419. func randomShadowsocksClientKey(method string) string {
  420. if n := shadowsocksKeyBytes(method); n > 0 {
  421. return random.Base64Bytes(n)
  422. }
  423. return strings.ReplaceAll(uuid.NewString(), "-", "")
  424. }
  425. func validShadowsocksClientKey(method, key string) bool {
  426. n := shadowsocksKeyBytes(method)
  427. if n == 0 {
  428. return key != ""
  429. }
  430. decoded, err := base64.StdEncoding.DecodeString(key)
  431. if err != nil {
  432. return false
  433. }
  434. return len(decoded) == n
  435. }
  436. func shadowsocksKeyBytes(method string) int {
  437. switch method {
  438. case "2022-blake3-aes-128-gcm":
  439. return 16
  440. case "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305":
  441. return 32
  442. }
  443. return 0
  444. }
  445. // normalizeShadowsocksClientKeys rewrites any Shadowsocks-2022 client password
  446. // whose decoded length no longer matches settings.method, which happens after the
  447. // inbound method is switched between ciphers of different key sizes (e.g.
  448. // aes-256↔aes-128). A wrong-length uPSK makes xray reject the user, so the link
  449. // fails to connect; regenerating restores a valid key (clients must re-fetch).
  450. // Non-Shadowsocks / legacy-SS settings pass through unchanged.
  451. func normalizeShadowsocksClientKeys(settings string) (string, bool) {
  452. method := shadowsocksMethodFromSettings(settings)
  453. if shadowsocksKeyBytes(method) == 0 {
  454. return settings, false
  455. }
  456. var m map[string]any
  457. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  458. return settings, false
  459. }
  460. clients, ok := m["clients"].([]any)
  461. if !ok {
  462. return settings, false
  463. }
  464. changed := false
  465. for i := range clients {
  466. c, ok := clients[i].(map[string]any)
  467. if !ok {
  468. continue
  469. }
  470. if pw, _ := c["password"].(string); validShadowsocksClientKey(method, pw) {
  471. continue
  472. }
  473. c["password"] = randomShadowsocksClientKey(method)
  474. clients[i] = c
  475. changed = true
  476. }
  477. if !changed {
  478. return settings, false
  479. }
  480. m["clients"] = clients
  481. bs, err := json.MarshalIndent(m, "", " ")
  482. if err != nil {
  483. return settings, false
  484. }
  485. return string(bs), true
  486. }
  487. func applyShadowsocksClientMethod(clients []any, settings map[string]any) {
  488. method, _ := settings["method"].(string)
  489. is2022 := strings.HasPrefix(method, "2022-blake3-")
  490. for i := range clients {
  491. cm, ok := clients[i].(map[string]any)
  492. if !ok {
  493. continue
  494. }
  495. if is2022 {
  496. if _, hasKey := cm["method"]; hasKey {
  497. delete(cm, "method")
  498. clients[i] = cm
  499. }
  500. continue
  501. }
  502. if method == "" {
  503. continue
  504. }
  505. if existing, _ := cm["method"].(string); existing != "" {
  506. continue
  507. }
  508. cm["method"] = method
  509. clients[i] = cm
  510. }
  511. }
  512. func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model.Client, limitHwid int, inboundFilter ...int) (bool, error) {
  513. existing, err := s.GetByID(id)
  514. if err != nil {
  515. return false, err
  516. }
  517. inboundIds, err := s.GetInboundIdsForRecord(id)
  518. if err != nil {
  519. return false, err
  520. }
  521. // The rename rewrites the one shared client record, so every node holding
  522. // this client goes stale — not just the ones an inboundIds filter applies.
  523. attachedIds := append([]int(nil), inboundIds...)
  524. if len(inboundFilter) > 0 {
  525. allow := make(map[int]struct{}, len(inboundFilter))
  526. for _, fid := range inboundFilter {
  527. allow[fid] = struct{}{}
  528. }
  529. filtered := inboundIds[:0:0]
  530. for _, ibId := range inboundIds {
  531. if _, ok := allow[ibId]; ok {
  532. filtered = append(filtered, ibId)
  533. }
  534. }
  535. inboundIds = filtered
  536. }
  537. if strings.TrimSpace(updated.Email) == "" {
  538. return false, common.NewError("client email is required")
  539. }
  540. if err := validateClientEmail(updated.Email); err != nil {
  541. return false, err
  542. }
  543. if err := validateClientSubID(updated.SubID); err != nil {
  544. return false, err
  545. }
  546. if err := validateClientResetDay(updated.ResetDay); err != nil {
  547. return false, err
  548. }
  549. if err := validateClientResetMax(updated.ResetMax); err != nil {
  550. return false, err
  551. }
  552. if err := validateClientTrafficReset(updated.TrafficReset, updated.TrafficResetDay); err != nil {
  553. return false, err
  554. }
  555. normalizeClientTrafficReset(&updated)
  556. if updated.SubID == "" {
  557. updated.SubID = existing.SubID
  558. }
  559. if updated.SubID == "" {
  560. updated.SubID = uuid.NewString()
  561. }
  562. updated.UpdatedAt = time.Now().UnixMilli()
  563. if updated.CreatedAt == 0 {
  564. updated.CreatedAt = existing.CreatedAt
  565. }
  566. // Preserve existing credentials when the caller omits them, so a partial
  567. // update (e.g. only changing traffic/expiry) doesn't silently rotate the
  568. // client's UUID/password/auth via fillProtocolDefaults. Supplying a new
  569. // value still rotates it intentionally.
  570. if updated.ID == "" {
  571. updated.ID = existing.UUID
  572. }
  573. if updated.Password == "" {
  574. updated.Password = existing.Password
  575. }
  576. if updated.Auth == "" {
  577. updated.Auth = existing.Auth
  578. }
  579. if updated.Secret == "" {
  580. updated.Secret = existing.Secret
  581. }
  582. if updated.Email != existing.Email {
  583. var collisionCount int64
  584. if err := database.GetDB().Model(&model.ClientRecord{}).
  585. Where("email = ? AND id <> ?", updated.Email, id).
  586. Count(&collisionCount).Error; err != nil {
  587. return false, err
  588. }
  589. if collisionCount > 0 {
  590. return false, common.NewError("Duplicate email:", updated.Email)
  591. }
  592. }
  593. if updated.SubID != existing.SubID {
  594. var subCollision int64
  595. if err := database.GetDB().Model(&model.ClientRecord{}).
  596. Where("sub_id = ? AND id <> ?", updated.SubID, id).
  597. Count(&subCollision).Error; err != nil {
  598. return false, err
  599. }
  600. if subCollision > 0 {
  601. return false, common.NewError("Duplicate subId:", updated.SubID)
  602. }
  603. }
  604. // Built before any inbound is written, as in Create: fillProtocolDefaults
  605. // mints the shared credentials on the first inbound, later ones reuse them.
  606. applies := make([]inboundApply, 0, len(inboundIds))
  607. for _, ibId := range inboundIds {
  608. inbound, getErr := inboundSvc.GetInbound(ibId)
  609. if getErr != nil {
  610. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  611. if err := database.GetDB().
  612. Where("client_id = ? AND inbound_id = ?", id, ibId).
  613. Delete(&model.ClientInbound{}).Error; err != nil {
  614. return false, err
  615. }
  616. continue
  617. }
  618. return false, getErr
  619. }
  620. if existing.Email == "" {
  621. continue
  622. }
  623. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  624. return false, err
  625. }
  626. clientForInbound := updated
  627. if ips, ok := updated.AllowedIPsByInbound[ibId]; ok {
  628. clientForInbound.AllowedIPs = ips
  629. } else if !addressesFitAmneziaWGInbound(clientForInbound.AllowedIPs, inbound) {
  630. // A single shared AllowedIPs field (the common case for a caller
  631. // that never sends AllowedIPsByInbound) must never overwrite an
  632. // inbound it doesn't belong to -- e.g. a client attached to both
  633. // wg and awg saving its wg-labeled address would otherwise get
  634. // that same address silently written into the awg peer config
  635. // too. Clearing it here makes UpdateInboundClient's own
  636. // empty-AllowedIPs carry-forward (see its WireGuard/AmneziaWG
  637. // branch) preserve THIS inbound's existing, correct value
  638. // instead.
  639. clientForInbound.AllowedIPs = nil
  640. }
  641. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(clientForInbound, inbound)}})
  642. if mErr != nil {
  643. return false, mErr
  644. }
  645. data := &model.Inbound{Id: ibId, Settings: string(settingsPayload)}
  646. applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) {
  647. return s.UpdateInboundClient(inboundSvc, data, existing.Email)
  648. }})
  649. }
  650. // Each apply marks only its OWN node dirty, so between the first and last
  651. // one a merge could resurrect the pre-edit email as a second client.
  652. if err := markInboundNodesDirty(attachedIds); err != nil {
  653. return false, err
  654. }
  655. needRestart, applyErr := fanoutInboundApplies(applies)
  656. if applyErr != nil {
  657. return needRestart, applyErr
  658. }
  659. // UpdateInboundClient renames the record atomically with each inbound's
  660. // settings JSON; this direct write only covers records with no inbound left.
  661. if updated.Email != existing.Email {
  662. if err := database.GetDB().Model(&model.ClientRecord{}).
  663. Where("id = ? AND email = ?", id, existing.Email).
  664. Update("email", updated.Email).Error; err != nil {
  665. return needRestart, err
  666. }
  667. }
  668. if len(inboundIds) == 0 {
  669. merged := *existing
  670. applyClientRecordMerge(&merged, updated.ToRecord())
  671. if err := database.GetDB().Model(&model.ClientRecord{}).
  672. Where("id = ?", id).
  673. Updates(map[string]any{
  674. "sub_id": merged.SubID,
  675. "uuid": merged.UUID,
  676. "password": merged.Password,
  677. "auth": merged.Auth,
  678. "secret": merged.Secret,
  679. "flow": merged.Flow,
  680. "security": merged.Security,
  681. "wg_private_key": merged.PrivateKey,
  682. "wg_public_key": merged.PublicKey,
  683. "wg_allowed_ips": merged.AllowedIPs,
  684. "wg_pre_shared_key": merged.PreSharedKey,
  685. "wg_keep_alive": merged.KeepAlive,
  686. "limit_ip": merged.LimitIP,
  687. "total_gb": merged.TotalGB,
  688. "expiry_time": merged.ExpiryTime,
  689. "tg_id": merged.TgID,
  690. "comment": merged.Comment,
  691. "reset": merged.Reset,
  692. "reset_day": merged.ResetDay,
  693. "reset_max": merged.ResetMax,
  694. "traffic_reset": merged.TrafficReset,
  695. "traffic_reset_day": merged.TrafficResetDay,
  696. }).Error; err != nil {
  697. return needRestart, err
  698. }
  699. }
  700. reverseStr := ""
  701. if updated.Reverse != nil && strings.TrimSpace(updated.Reverse.Tag) != "" {
  702. if b, mErr := json.Marshal(updated.Reverse); mErr == nil {
  703. reverseStr = string(b)
  704. }
  705. }
  706. if err := database.GetDB().Model(&model.ClientRecord{}).
  707. Where("id = ?", id).
  708. Update("reverse", reverseStr).Error; err != nil {
  709. return needRestart, err
  710. }
  711. // Persist the group explicitly. SyncInbound deliberately preserves the
  712. // stored group when the inbound settings carry none — so a node snapshot or a
  713. // group-less settings rebuild can't wipe it (see SyncInbound + its tests).
  714. // That guard also meant clearing the group in the client editor never took
  715. // effect. The editor always round-trips the field, so apply it here,
  716. // including the empty string that removes the client from its group.
  717. if err := database.GetDB().Model(&model.ClientRecord{}).
  718. Where("id = ?", id).
  719. UpdateColumn("group_name", updated.Group).Error; err != nil {
  720. return needRestart, err
  721. }
  722. // Same shape as the group write above: SyncInbound keeps a stored ad-tag
  723. // when the incoming settings carry none, so clearing the override must be
  724. // applied here, where the editor always round-trips the field.
  725. if err := database.GetDB().Model(&model.ClientRecord{}).
  726. Where("id = ?", id).
  727. UpdateColumn("ad_tag", updated.AdTag).Error; err != nil {
  728. return needRestart, err
  729. }
  730. if err := database.GetDB().Model(&model.ClientRecord{}).
  731. Where("id = ?", id).
  732. UpdateColumn("enable", updated.Enable).Error; err != nil {
  733. return needRestart, err
  734. }
  735. if err := s.setClientLimitHwidByEmail(nil, updated.Email, limitHwid); err != nil {
  736. return needRestart, err
  737. }
  738. if err := database.GetDB().Model(&model.ClientRecord{}).
  739. Where("id = ?", id).
  740. UpdateColumn("updated_at", time.Now().UnixMilli()).Error; err != nil {
  741. return needRestart, err
  742. }
  743. return needRestart, nil
  744. }
  745. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  746. existing, err := s.GetByID(id)
  747. if err != nil {
  748. return false, err
  749. }
  750. tombstoneClientEmail(existing.Email)
  751. inboundIds, err := s.GetInboundIdsForRecord(id)
  752. if err != nil {
  753. withdrawClientTombstones(existing.Email)
  754. return false, err
  755. }
  756. applies := make([]inboundApply, 0, len(inboundIds))
  757. var delErrs []error
  758. for _, ibId := range inboundIds {
  759. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  760. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  761. continue
  762. }
  763. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, getErr))
  764. continue
  765. }
  766. // Always delete by email — the client's stable identity. This removes
  767. // every matching entry from the inbound's settings even when the stored
  768. // credential (UUID/password/auth) drifted from the inbound JSON, or a
  769. // duplicate entry with the same email exists.
  770. if existing.Email == "" {
  771. continue
  772. }
  773. applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) {
  774. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, keepTraffic, true)
  775. // The client is already absent from this inbound (data drift or a
  776. // retried delete). Skip it — deletion stays idempotent.
  777. if errors.Is(delErr, ErrClientNotInInbound) {
  778. return nr, nil
  779. }
  780. return nr, delErr
  781. }})
  782. }
  783. needRestart, applyErr := fanoutInboundApplies(applies)
  784. if applyErr != nil {
  785. delErrs = append(delErrs, applyErr)
  786. }
  787. // A failed inbound still holds the client in its settings JSON: keep the
  788. // record so the next delete retries exactly the leftovers, and report it.
  789. // The tombstone lifts with it, or the next node merge finishes the deletion.
  790. if len(delErrs) > 0 {
  791. withdrawClientTombstones(existing.Email)
  792. return needRestart, errors.Join(delErrs...)
  793. }
  794. db := database.GetDB()
  795. if err := db.Transaction(func(tx *gorm.DB) error {
  796. if existing.Email != "" {
  797. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{existing.Email}); err != nil {
  798. return err
  799. }
  800. }
  801. if err := tx.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  802. return err
  803. }
  804. if err := tx.Where("client_id = ?", id).Delete(&model.ClientExternalLink{}).Error; err != nil {
  805. return err
  806. }
  807. if err := clearClientHwidsBySubIDTx(tx, existing.SubID); err != nil {
  808. return err
  809. }
  810. if !keepTraffic && existing.Email != "" {
  811. if err := tx.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  812. return err
  813. }
  814. if err := clearGlobalTraffic(tx, existing.Email); err != nil {
  815. return err
  816. }
  817. if err := tx.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  818. return err
  819. }
  820. if err := tx.Where("email = ?", existing.Email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  821. return err
  822. }
  823. }
  824. return tx.Delete(&model.ClientRecord{}, id).Error
  825. }); err != nil {
  826. withdrawClientTombstones(existing.Email)
  827. return needRestart, err
  828. }
  829. return needRestart, nil
  830. }
  831. // hasTunnelAttachment reports whether any of inboundIds is a currently
  832. // existing WireGuard or AmneziaWG inbound. Inbounds that fail to load are
  833. // skipped rather than treated as an error -- Attach's own loop already
  834. // surfaces a real error for any inbound it can't load when it gets there.
  835. func (s *ClientService) hasTunnelAttachment(inboundSvc *InboundService, inboundIds []int) bool {
  836. for _, ibId := range inboundIds {
  837. inbound, err := inboundSvc.GetInbound(ibId)
  838. if err != nil {
  839. continue
  840. }
  841. if inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG {
  842. return true
  843. }
  844. }
  845. return false
  846. }
  847. // addressesFitAmneziaWGInbound reports whether every entry in addrs falls
  848. // inside ib's own configured subnet(s). AmneziaWG only: its kernel interface
  849. // Address is exactly that subnet, so an address inherited from elsewhere (an
  850. // identity attached to a WireGuard inbound first, say) produces a peer that
  851. // can never connect -- Attach allocates fresh instead.
  852. func addressesFitAmneziaWGInbound(addrs []string, ib *model.Inbound) bool {
  853. if ib.Protocol != model.AmneziaWG || len(addrs) == 0 {
  854. return true
  855. }
  856. v4Base, v6Base, err := defaultAmneziaWGSubnetBases(ib.Settings)
  857. if err != nil {
  858. return false
  859. }
  860. bases := make([]netip.Prefix, 0, 2)
  861. for _, base := range []string{v4Base, v6Base} {
  862. if base == "" {
  863. continue
  864. }
  865. prefix, pErr := netip.ParsePrefix(base)
  866. if pErr != nil {
  867. return false
  868. }
  869. bases = append(bases, prefix)
  870. }
  871. for _, a := range addrs {
  872. host := wireguardHostAddr(a)
  873. if !host.IsValid() {
  874. return false
  875. }
  876. fits := false
  877. for _, prefix := range bases {
  878. if prefix.Contains(host) {
  879. fits = true
  880. break
  881. }
  882. }
  883. if !fits {
  884. return false
  885. }
  886. }
  887. return true
  888. }
  889. // Attach applies the client to every requested inbound: one failing inbound no
  890. // longer aborts the others, so the error can name several and needRestart holds.
  891. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  892. existing, err := s.GetByID(id)
  893. if err != nil {
  894. return false, err
  895. }
  896. currentIds, err := s.GetInboundIdsForRecord(id)
  897. if err != nil {
  898. return false, err
  899. }
  900. have := make(map[int]struct{}, len(currentIds))
  901. for _, x := range currentIds {
  902. have[x] = struct{}{}
  903. }
  904. clientWire := existing.ToClient()
  905. flow, ffErr := s.EffectiveFlow(nil, id)
  906. if ffErr != nil {
  907. return false, ffErr
  908. }
  909. clientWire.Flow = flow
  910. clientWire.UpdatedAt = time.Now().UnixMilli()
  911. // If this identity has no CURRENT WireGuard/AmneziaWG attachment,
  912. // clientWire.AllowedIPs (from the ClientRecord) is a leftover from
  913. // whenever it last had one -- nothing reserves it anymore. Clear it so
  914. // attaching to a tunnel inbound now allocates a fresh address instead
  915. // of resurrecting the old one, which may no longer even be the lowest
  916. // free slot. Left untouched when the identity already has an active
  917. // tunnel elsewhere, so extending it to a second protocol still keeps
  918. // the same address on both.
  919. if !s.hasTunnelAttachment(inboundSvc, currentIds) {
  920. clientWire.AllowedIPs = nil
  921. }
  922. adds := make([]*model.Inbound, 0, len(inboundIds))
  923. for _, ibId := range inboundIds {
  924. if _, attached := have[ibId]; attached {
  925. continue
  926. }
  927. inbound, getErr := inboundSvc.GetInbound(ibId)
  928. if getErr != nil {
  929. return false, fmt.Errorf("inbound %d: %w", ibId, getErr)
  930. }
  931. copyClient := *clientWire
  932. if !addressesFitAmneziaWGInbound(copyClient.AllowedIPs, inbound) {
  933. copyClient.AllowedIPs = nil
  934. }
  935. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  936. return false, fmt.Errorf("inbound %d: %w", ibId, err)
  937. }
  938. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}})
  939. if mErr != nil {
  940. return false, fmt.Errorf("inbound %d: %w", ibId, mErr)
  941. }
  942. adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload)})
  943. }
  944. return s.fanoutInboundClientAdds(inboundSvc, adds)
  945. }
  946. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  947. return s.Create(inboundSvc, &ClientCreatePayload{
  948. Client: client,
  949. InboundIds: []int{inboundId},
  950. })
  951. }
  952. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  953. if email == "" {
  954. return false, common.NewError("client email is required")
  955. }
  956. rec, err := s.GetRecordByEmail(nil, email)
  957. if err != nil {
  958. return false, err
  959. }
  960. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  961. }
  962. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  963. if email == "" {
  964. return false, common.NewError("client email is required")
  965. }
  966. rec, err := s.GetRecordByEmail(nil, email)
  967. if err != nil {
  968. return false, err
  969. }
  970. return s.Attach(inboundSvc, rec.Id, inboundIds)
  971. }
  972. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  973. if email == "" {
  974. return false, common.NewError("client email is required")
  975. }
  976. rec, err := s.GetRecordByEmail(nil, email)
  977. if err != nil {
  978. return false, err
  979. }
  980. return s.Detach(inboundSvc, rec.Id, inboundIds)
  981. }
  982. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  983. if email == "" {
  984. return false, common.NewError("client email is required")
  985. }
  986. rec, err := s.GetRecordByEmail(nil, email)
  987. if err == nil {
  988. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  989. }
  990. if !errors.Is(err, gorm.ErrRecordNotFound) {
  991. return false, err
  992. }
  993. inboundIds, idsErr := s.findInboundIdsByClientEmail(email)
  994. if idsErr != nil {
  995. return false, idsErr
  996. }
  997. if len(inboundIds) == 0 {
  998. return false, common.NewError(fmt.Sprintf("client %q not found in any inbound or client record", email))
  999. }
  1000. applies := make([]inboundApply, 0, len(inboundIds))
  1001. for _, ibId := range inboundIds {
  1002. applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) {
  1003. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, email, keepTraffic, true)
  1004. if errors.Is(delErr, ErrClientNotInInbound) {
  1005. return nr, nil
  1006. }
  1007. return nr, delErr
  1008. }})
  1009. }
  1010. needRestart, delErr := fanoutInboundApplies(applies)
  1011. if delErr != nil {
  1012. return needRestart, delErr
  1013. }
  1014. if !keepTraffic {
  1015. db := database.GetDB()
  1016. if err := db.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  1017. return needRestart, err
  1018. }
  1019. if err := clearGlobalTraffic(db, email); err != nil {
  1020. return needRestart, err
  1021. }
  1022. if err := db.Where("client_email = ?", email).Delete(&model.InboundClientIps{}).Error; err != nil {
  1023. return needRestart, err
  1024. }
  1025. if err := db.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  1026. return needRestart, err
  1027. }
  1028. }
  1029. return needRestart, nil
  1030. }
  1031. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client, limitHwid int, inboundFilter ...int) (bool, error) {
  1032. if email == "" {
  1033. return false, common.NewError("client email is required")
  1034. }
  1035. rec, err := s.GetRecordByEmail(nil, email)
  1036. if err != nil {
  1037. return false, err
  1038. }
  1039. return s.Update(inboundSvc, rec.Id, updated, limitHwid, inboundFilter...)
  1040. }
  1041. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  1042. existing, err := s.GetByID(id)
  1043. if err != nil {
  1044. return false, err
  1045. }
  1046. currentIds, err := s.GetInboundIdsForRecord(id)
  1047. if err != nil {
  1048. return false, err
  1049. }
  1050. have := make(map[int]struct{}, len(currentIds))
  1051. for _, x := range currentIds {
  1052. have[x] = struct{}{}
  1053. }
  1054. applies := make([]inboundApply, 0, len(inboundIds))
  1055. for _, ibId := range inboundIds {
  1056. if _, attached := have[ibId]; !attached {
  1057. continue
  1058. }
  1059. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  1060. return false, getErr
  1061. }
  1062. // Detach by email — the client's stable identity (see Delete).
  1063. if existing.Email == "" {
  1064. continue
  1065. }
  1066. applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) {
  1067. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, true, false)
  1068. if errors.Is(delErr, ErrClientNotInInbound) {
  1069. return nr, nil
  1070. }
  1071. return nr, delErr
  1072. }})
  1073. }
  1074. return fanoutInboundApplies(applies)
  1075. }