1
0

client_crud.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. package service
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "strings"
  8. "time"
  9. "unicode"
  10. "github.com/google/uuid"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  13. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  14. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  15. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  16. "gorm.io/gorm"
  17. )
  18. func hasForbiddenClientChar(s string) bool {
  19. for _, r := range s {
  20. if r == '/' || r == '\\' || r < 0x20 || r == 0x7f || unicode.IsSpace(r) {
  21. return true
  22. }
  23. }
  24. return false
  25. }
  26. func validateClientEmail(email string) error {
  27. if hasForbiddenClientChar(email) {
  28. return common.NewError("client email contains an invalid character:", email)
  29. }
  30. return nil
  31. }
  32. func validateClientSubID(subID string) error {
  33. if hasForbiddenClientChar(subID) {
  34. return common.NewError("client subId contains an invalid character:", subID)
  35. }
  36. return nil
  37. }
  38. // Rejected rather than coerced: an unknown cycle would leave the operator with
  39. // a field that reads as configured while no job ever selects the client.
  40. func validateClientTrafficReset(period string, day int) error {
  41. switch period {
  42. case "", "never", "hourly", "daily", "weekly", "monthly":
  43. default:
  44. return common.NewError("client trafficReset must be never, hourly, daily, weekly or monthly, got:", period)
  45. }
  46. if day < 0 || day > 31 {
  47. return common.NewError("client trafficResetDay must be between 0 and 31, got:", day)
  48. }
  49. return nil
  50. }
  51. // Rejected rather than clamped: nextCalendarRenewal would silently move an
  52. // out-of-range day, and a negative one drops out of the renewal query entirely.
  53. func validateClientResetDay(day int) error {
  54. if day < 0 || day > 31 {
  55. return common.NewError("client resetDay must be between 0 and 31, got:", day)
  56. }
  57. return nil
  58. }
  59. // Rejected rather than coerced: a negative cap reads as "unlimited" to a caller
  60. // but selects nothing, so the client would silently stop renewing.
  61. func validateClientResetMax(resetMax int) error {
  62. if resetMax < 0 {
  63. return common.NewError("client resetMax must not be negative, got:", resetMax)
  64. }
  65. return nil
  66. }
  67. // normalizeClientTrafficReset stores what the inbound path would store, so the
  68. // day never reaches the DB as a 0 that three layers downstream each clamp to 1.
  69. func normalizeClientTrafficReset(c *model.Client) {
  70. if c.TrafficReset == "" {
  71. c.TrafficReset = "never"
  72. }
  73. c.TrafficResetDay = normalizeTrafficResetDay(c.TrafficResetDay)
  74. }
  75. // ClientResetCycle is the slice of a client the reset job needs: enough to know
  76. // whether it is due, and whether its disable is the quota's doing or the operator's.
  77. type ClientResetCycle struct {
  78. Email string
  79. TrafficResetDay int
  80. Enable bool
  81. Total int64
  82. Used int64
  83. }
  84. // Depleted reports a client the quota switched off. A reset restores that one;
  85. // a client disabled below its quota was switched off by hand and stays off.
  86. func (c ClientResetCycle) Depleted() bool {
  87. return c.Total > 0 && c.Used >= c.Total
  88. }
  89. // GetClientsByTrafficReset returns the clients whose own reset cycle matches the
  90. // period, independent of the cycle configured on the inbounds they belong to.
  91. func (s *ClientService) GetClientsByTrafficReset(period string) ([]ClientResetCycle, error) {
  92. var cycles []ClientResetCycle
  93. err := database.GetDB().Table("clients c").
  94. 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").
  95. Joins("LEFT JOIN client_traffics ct ON ct.email = c.email").
  96. Where("c.traffic_reset = ?", period).
  97. Scan(&cycles).Error
  98. if err != nil {
  99. return nil, err
  100. }
  101. return cycles, nil
  102. }
  103. func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) {
  104. if payload == nil {
  105. return false, common.NewError("empty payload")
  106. }
  107. client := payload.Client
  108. if strings.TrimSpace(client.Email) == "" {
  109. return false, common.NewError("client email is required")
  110. }
  111. if err := validateClientEmail(client.Email); err != nil {
  112. return false, err
  113. }
  114. if err := validateClientSubID(client.SubID); err != nil {
  115. return false, err
  116. }
  117. if err := validateClientResetDay(client.ResetDay); err != nil {
  118. return false, err
  119. }
  120. if err := validateClientResetMax(client.ResetMax); err != nil {
  121. return false, err
  122. }
  123. if err := validateClientTrafficReset(client.TrafficReset, client.TrafficResetDay); err != nil {
  124. return false, err
  125. }
  126. normalizeClientTrafficReset(&client)
  127. if len(payload.InboundIds) == 0 {
  128. return false, common.NewError("at least one inbound is required")
  129. }
  130. if client.SubID == "" {
  131. client.SubID = uuid.NewString()
  132. }
  133. if !client.Enable {
  134. client.Enable = true
  135. }
  136. now := time.Now().UnixMilli()
  137. if client.CreatedAt == 0 {
  138. client.CreatedAt = now
  139. }
  140. client.UpdatedAt = now
  141. existing := &model.ClientRecord{}
  142. err := database.GetDB().Where("email = ?", client.Email).First(existing).Error
  143. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  144. return false, err
  145. }
  146. emailTaken := !errors.Is(err, gorm.ErrRecordNotFound)
  147. if emailTaken {
  148. if existing.SubID == "" || existing.SubID != client.SubID {
  149. return false, common.NewError("email already in use:", client.Email)
  150. }
  151. // Reuse stored credentials when re-adding an existing identity, or
  152. // fillProtocolDefaults mints a fresh UUID that desyncs other inbounds.
  153. if client.ID == "" {
  154. client.ID = existing.UUID
  155. }
  156. if client.Password == "" {
  157. client.Password = existing.Password
  158. }
  159. if client.Auth == "" {
  160. client.Auth = existing.Auth
  161. }
  162. if client.Secret == "" {
  163. client.Secret = existing.Secret
  164. }
  165. }
  166. if client.SubID != "" {
  167. var subTaken int64
  168. if err := database.GetDB().Model(&model.ClientRecord{}).
  169. Where("sub_id = ? AND email <> ?", client.SubID, client.Email).
  170. Count(&subTaken).Error; err != nil {
  171. return false, err
  172. }
  173. if subTaken > 0 {
  174. return false, common.NewError("subId already in use:", client.SubID)
  175. }
  176. }
  177. needRestart := false
  178. for _, ibId := range payload.InboundIds {
  179. inbound, getErr := inboundSvc.GetInbound(ibId)
  180. if getErr != nil {
  181. return needRestart, getErr
  182. }
  183. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  184. return needRestart, err
  185. }
  186. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(client, inbound)}})
  187. if mErr != nil {
  188. return needRestart, mErr
  189. }
  190. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  191. Id: ibId,
  192. Settings: string(settingsPayload),
  193. })
  194. if addErr != nil {
  195. return needRestart, addErr
  196. }
  197. if nr {
  198. needRestart = true
  199. }
  200. }
  201. if err := s.setClientLimitHwidByEmail(nil, client.Email, payload.LimitHwid); err != nil {
  202. return needRestart, err
  203. }
  204. return needRestart, nil
  205. }
  206. func (s *ClientService) fillProtocolDefaults(c *model.Client, ib *model.Inbound) error {
  207. switch ib.Protocol {
  208. case model.VMESS, model.VLESS:
  209. if c.ID == "" {
  210. c.ID = uuid.NewString()
  211. }
  212. case model.Trojan:
  213. if c.Password == "" {
  214. c.Password = strings.ReplaceAll(uuid.NewString(), "-", "")
  215. }
  216. case model.Shadowsocks:
  217. method := shadowsocksMethodFromSettings(ib.Settings)
  218. if c.Password == "" || !validShadowsocksClientKey(method, c.Password) {
  219. c.Password = randomShadowsocksClientKey(method)
  220. }
  221. case model.Hysteria:
  222. if c.Auth == "" {
  223. c.Auth = strings.ReplaceAll(uuid.NewString(), "-", "")
  224. }
  225. case model.MTProto:
  226. if c.Secret == "" {
  227. c.Secret = model.GenerateFakeTLSSecret(mtprotoDomainFromSettings(ib.Settings))
  228. }
  229. }
  230. return nil
  231. }
  232. // defaultMtprotoDomain is the FakeTLS fronting domain used when an mtproto
  233. // inbound carries no fakeTlsDomain of its own; it mirrors the frontend default.
  234. const defaultMtprotoDomain = "www.cloudflare.com"
  235. // mtprotoDomainFromSettings returns the inbound-level FakeTLS domain, falling
  236. // back to the default when unset, so a generated client secret always fronts a
  237. // real hostname.
  238. func mtprotoDomainFromSettings(settings string) string {
  239. domain := ""
  240. if settings != "" {
  241. var m map[string]any
  242. if err := json.Unmarshal([]byte(settings), &m); err == nil {
  243. domain, _ = m["fakeTlsDomain"].(string)
  244. }
  245. }
  246. domain = strings.TrimSpace(domain)
  247. if domain == "" {
  248. return defaultMtprotoDomain
  249. }
  250. return domain
  251. }
  252. func clientWithInboundFlow(c model.Client, ib *model.Inbound) model.Client {
  253. if ib.DisableFlow || !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings) {
  254. c.Flow = ""
  255. }
  256. return c
  257. }
  258. func shadowsocksMethodFromSettings(settings string) string {
  259. if settings == "" {
  260. return ""
  261. }
  262. var m map[string]any
  263. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  264. return ""
  265. }
  266. method, _ := m["method"].(string)
  267. return method
  268. }
  269. func randomShadowsocksClientKey(method string) string {
  270. if n := shadowsocksKeyBytes(method); n > 0 {
  271. return random.Base64Bytes(n)
  272. }
  273. return strings.ReplaceAll(uuid.NewString(), "-", "")
  274. }
  275. func validShadowsocksClientKey(method, key string) bool {
  276. n := shadowsocksKeyBytes(method)
  277. if n == 0 {
  278. return key != ""
  279. }
  280. decoded, err := base64.StdEncoding.DecodeString(key)
  281. if err != nil {
  282. return false
  283. }
  284. return len(decoded) == n
  285. }
  286. func shadowsocksKeyBytes(method string) int {
  287. switch method {
  288. case "2022-blake3-aes-128-gcm":
  289. return 16
  290. case "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305":
  291. return 32
  292. }
  293. return 0
  294. }
  295. // normalizeShadowsocksClientKeys rewrites any Shadowsocks-2022 client password
  296. // whose decoded length no longer matches settings.method, which happens after the
  297. // inbound method is switched between ciphers of different key sizes (e.g.
  298. // aes-256↔aes-128). A wrong-length uPSK makes xray reject the user, so the link
  299. // fails to connect; regenerating restores a valid key (clients must re-fetch).
  300. // Non-Shadowsocks / legacy-SS settings pass through unchanged.
  301. func normalizeShadowsocksClientKeys(settings string) (string, bool) {
  302. method := shadowsocksMethodFromSettings(settings)
  303. if shadowsocksKeyBytes(method) == 0 {
  304. return settings, false
  305. }
  306. var m map[string]any
  307. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  308. return settings, false
  309. }
  310. clients, ok := m["clients"].([]any)
  311. if !ok {
  312. return settings, false
  313. }
  314. changed := false
  315. for i := range clients {
  316. c, ok := clients[i].(map[string]any)
  317. if !ok {
  318. continue
  319. }
  320. if pw, _ := c["password"].(string); validShadowsocksClientKey(method, pw) {
  321. continue
  322. }
  323. c["password"] = randomShadowsocksClientKey(method)
  324. clients[i] = c
  325. changed = true
  326. }
  327. if !changed {
  328. return settings, false
  329. }
  330. m["clients"] = clients
  331. bs, err := json.MarshalIndent(m, "", " ")
  332. if err != nil {
  333. return settings, false
  334. }
  335. return string(bs), true
  336. }
  337. func applyShadowsocksClientMethod(clients []any, settings map[string]any) {
  338. method, _ := settings["method"].(string)
  339. is2022 := strings.HasPrefix(method, "2022-blake3-")
  340. for i := range clients {
  341. cm, ok := clients[i].(map[string]any)
  342. if !ok {
  343. continue
  344. }
  345. if is2022 {
  346. if _, hasKey := cm["method"]; hasKey {
  347. delete(cm, "method")
  348. clients[i] = cm
  349. }
  350. continue
  351. }
  352. if method == "" {
  353. continue
  354. }
  355. if existing, _ := cm["method"].(string); existing != "" {
  356. continue
  357. }
  358. cm["method"] = method
  359. clients[i] = cm
  360. }
  361. }
  362. func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model.Client, limitHwid int, inboundFilter ...int) (bool, error) {
  363. existing, err := s.GetByID(id)
  364. if err != nil {
  365. return false, err
  366. }
  367. inboundIds, err := s.GetInboundIdsForRecord(id)
  368. if err != nil {
  369. return false, err
  370. }
  371. if len(inboundFilter) > 0 {
  372. allow := make(map[int]struct{}, len(inboundFilter))
  373. for _, fid := range inboundFilter {
  374. allow[fid] = struct{}{}
  375. }
  376. filtered := inboundIds[:0:0]
  377. for _, ibId := range inboundIds {
  378. if _, ok := allow[ibId]; ok {
  379. filtered = append(filtered, ibId)
  380. }
  381. }
  382. inboundIds = filtered
  383. }
  384. if strings.TrimSpace(updated.Email) == "" {
  385. return false, common.NewError("client email is required")
  386. }
  387. if err := validateClientEmail(updated.Email); err != nil {
  388. return false, err
  389. }
  390. if err := validateClientSubID(updated.SubID); err != nil {
  391. return false, err
  392. }
  393. if err := validateClientResetDay(updated.ResetDay); err != nil {
  394. return false, err
  395. }
  396. if err := validateClientResetMax(updated.ResetMax); err != nil {
  397. return false, err
  398. }
  399. if err := validateClientTrafficReset(updated.TrafficReset, updated.TrafficResetDay); err != nil {
  400. return false, err
  401. }
  402. normalizeClientTrafficReset(&updated)
  403. if updated.SubID == "" {
  404. updated.SubID = existing.SubID
  405. }
  406. if updated.SubID == "" {
  407. updated.SubID = uuid.NewString()
  408. }
  409. updated.UpdatedAt = time.Now().UnixMilli()
  410. if updated.CreatedAt == 0 {
  411. updated.CreatedAt = existing.CreatedAt
  412. }
  413. // Preserve existing credentials when the caller omits them, so a partial
  414. // update (e.g. only changing traffic/expiry) doesn't silently rotate the
  415. // client's UUID/password/auth via fillProtocolDefaults. Supplying a new
  416. // value still rotates it intentionally.
  417. if updated.ID == "" {
  418. updated.ID = existing.UUID
  419. }
  420. if updated.Password == "" {
  421. updated.Password = existing.Password
  422. }
  423. if updated.Auth == "" {
  424. updated.Auth = existing.Auth
  425. }
  426. if updated.Secret == "" {
  427. updated.Secret = existing.Secret
  428. }
  429. if updated.Email != existing.Email {
  430. var collisionCount int64
  431. if err := database.GetDB().Model(&model.ClientRecord{}).
  432. Where("email = ? AND id <> ?", updated.Email, id).
  433. Count(&collisionCount).Error; err != nil {
  434. return false, err
  435. }
  436. if collisionCount > 0 {
  437. return false, common.NewError("Duplicate email:", updated.Email)
  438. }
  439. }
  440. if updated.SubID != existing.SubID {
  441. var subCollision int64
  442. if err := database.GetDB().Model(&model.ClientRecord{}).
  443. Where("sub_id = ? AND id <> ?", updated.SubID, id).
  444. Count(&subCollision).Error; err != nil {
  445. return false, err
  446. }
  447. if subCollision > 0 {
  448. return false, common.NewError("Duplicate subId:", updated.SubID)
  449. }
  450. }
  451. needRestart := false
  452. for _, ibId := range inboundIds {
  453. inbound, getErr := inboundSvc.GetInbound(ibId)
  454. if getErr != nil {
  455. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  456. if err := database.GetDB().
  457. Where("client_id = ? AND inbound_id = ?", id, ibId).
  458. Delete(&model.ClientInbound{}).Error; err != nil {
  459. return needRestart, err
  460. }
  461. continue
  462. }
  463. return needRestart, getErr
  464. }
  465. if existing.Email == "" {
  466. continue
  467. }
  468. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  469. return needRestart, err
  470. }
  471. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(updated, inbound)}})
  472. if mErr != nil {
  473. return needRestart, mErr
  474. }
  475. nr, upErr := s.UpdateInboundClient(inboundSvc, &model.Inbound{
  476. Id: ibId,
  477. Settings: string(settingsPayload),
  478. }, existing.Email)
  479. if upErr != nil {
  480. return needRestart, upErr
  481. }
  482. if nr {
  483. needRestart = true
  484. }
  485. }
  486. // UpdateInboundClient renames the record atomically with each inbound's
  487. // settings JSON; this direct write only covers records with no inbound left.
  488. if updated.Email != existing.Email {
  489. if err := database.GetDB().Model(&model.ClientRecord{}).
  490. Where("id = ? AND email = ?", id, existing.Email).
  491. Update("email", updated.Email).Error; err != nil {
  492. return needRestart, err
  493. }
  494. }
  495. if len(inboundIds) == 0 {
  496. merged := *existing
  497. applyClientRecordMerge(&merged, updated.ToRecord())
  498. if err := database.GetDB().Model(&model.ClientRecord{}).
  499. Where("id = ?", id).
  500. Updates(map[string]any{
  501. "sub_id": merged.SubID,
  502. "uuid": merged.UUID,
  503. "password": merged.Password,
  504. "auth": merged.Auth,
  505. "secret": merged.Secret,
  506. "flow": merged.Flow,
  507. "security": merged.Security,
  508. "wg_private_key": merged.PrivateKey,
  509. "wg_public_key": merged.PublicKey,
  510. "wg_allowed_ips": merged.AllowedIPs,
  511. "wg_pre_shared_key": merged.PreSharedKey,
  512. "wg_keep_alive": merged.KeepAlive,
  513. "limit_ip": merged.LimitIP,
  514. "total_gb": merged.TotalGB,
  515. "expiry_time": merged.ExpiryTime,
  516. "tg_id": merged.TgID,
  517. "comment": merged.Comment,
  518. "reset": merged.Reset,
  519. "reset_day": merged.ResetDay,
  520. "reset_max": merged.ResetMax,
  521. "traffic_reset": merged.TrafficReset,
  522. "traffic_reset_day": merged.TrafficResetDay,
  523. }).Error; err != nil {
  524. return needRestart, err
  525. }
  526. }
  527. reverseStr := ""
  528. if updated.Reverse != nil && strings.TrimSpace(updated.Reverse.Tag) != "" {
  529. if b, mErr := json.Marshal(updated.Reverse); mErr == nil {
  530. reverseStr = string(b)
  531. }
  532. }
  533. if err := database.GetDB().Model(&model.ClientRecord{}).
  534. Where("id = ?", id).
  535. Update("reverse", reverseStr).Error; err != nil {
  536. return needRestart, err
  537. }
  538. // Persist the group explicitly. SyncInbound deliberately preserves the
  539. // stored group when the inbound settings carry none — so a node snapshot or a
  540. // group-less settings rebuild can't wipe it (see SyncInbound + its tests).
  541. // That guard also meant clearing the group in the client editor never took
  542. // effect. The editor always round-trips the field, so apply it here,
  543. // including the empty string that removes the client from its group.
  544. if err := database.GetDB().Model(&model.ClientRecord{}).
  545. Where("id = ?", id).
  546. UpdateColumn("group_name", updated.Group).Error; err != nil {
  547. return needRestart, err
  548. }
  549. // Same shape as the group write above: SyncInbound keeps a stored ad-tag
  550. // when the incoming settings carry none, so clearing the override must be
  551. // applied here, where the editor always round-trips the field.
  552. if err := database.GetDB().Model(&model.ClientRecord{}).
  553. Where("id = ?", id).
  554. UpdateColumn("ad_tag", updated.AdTag).Error; err != nil {
  555. return needRestart, err
  556. }
  557. if err := database.GetDB().Model(&model.ClientRecord{}).
  558. Where("id = ?", id).
  559. UpdateColumn("enable", updated.Enable).Error; err != nil {
  560. return needRestart, err
  561. }
  562. if err := s.setClientLimitHwidByEmail(nil, updated.Email, limitHwid); err != nil {
  563. return needRestart, err
  564. }
  565. if err := database.GetDB().Model(&model.ClientRecord{}).
  566. Where("id = ?", id).
  567. UpdateColumn("updated_at", time.Now().UnixMilli()).Error; err != nil {
  568. return needRestart, err
  569. }
  570. return needRestart, nil
  571. }
  572. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  573. existing, err := s.GetByID(id)
  574. if err != nil {
  575. return false, err
  576. }
  577. tombstoneClientEmail(existing.Email)
  578. inboundIds, err := s.GetInboundIdsForRecord(id)
  579. if err != nil {
  580. withdrawClientTombstones(existing.Email)
  581. return false, err
  582. }
  583. needRestart := false
  584. var delErrs []error
  585. for _, ibId := range inboundIds {
  586. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  587. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  588. continue
  589. }
  590. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, getErr))
  591. continue
  592. }
  593. // Always delete by email — the client's stable identity. This removes
  594. // every matching entry from the inbound's settings even when the stored
  595. // credential (UUID/password/auth) drifted from the inbound JSON, or a
  596. // duplicate entry with the same email exists.
  597. if existing.Email == "" {
  598. continue
  599. }
  600. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, keepTraffic, true)
  601. if delErr != nil {
  602. // The client is already absent from this inbound (data drift or a
  603. // retried delete). Skip it — deletion stays idempotent.
  604. if errors.Is(delErr, ErrClientNotInInbound) {
  605. continue
  606. }
  607. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, delErr))
  608. continue
  609. }
  610. if nr {
  611. needRestart = true
  612. }
  613. }
  614. // A failed inbound still holds the client in its settings JSON: keep the
  615. // record so the next delete retries exactly the leftovers, and report it.
  616. // The tombstone lifts with it, or the next node merge finishes the deletion.
  617. if len(delErrs) > 0 {
  618. withdrawClientTombstones(existing.Email)
  619. return needRestart, errors.Join(delErrs...)
  620. }
  621. db := database.GetDB()
  622. if err := db.Transaction(func(tx *gorm.DB) error {
  623. if existing.Email != "" {
  624. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{existing.Email}); err != nil {
  625. return err
  626. }
  627. }
  628. if err := tx.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  629. return err
  630. }
  631. if err := tx.Where("client_id = ?", id).Delete(&model.ClientExternalLink{}).Error; err != nil {
  632. return err
  633. }
  634. if err := clearClientHwidsBySubIDTx(tx, existing.SubID); err != nil {
  635. return err
  636. }
  637. if !keepTraffic && existing.Email != "" {
  638. if err := tx.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  639. return err
  640. }
  641. if err := clearGlobalTraffic(tx, existing.Email); err != nil {
  642. return err
  643. }
  644. if err := tx.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  645. return err
  646. }
  647. if err := tx.Where("email = ?", existing.Email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  648. return err
  649. }
  650. }
  651. return tx.Delete(&model.ClientRecord{}, id).Error
  652. }); err != nil {
  653. withdrawClientTombstones(existing.Email)
  654. return needRestart, err
  655. }
  656. return needRestart, nil
  657. }
  658. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  659. existing, err := s.GetByID(id)
  660. if err != nil {
  661. return false, err
  662. }
  663. currentIds, err := s.GetInboundIdsForRecord(id)
  664. if err != nil {
  665. return false, err
  666. }
  667. have := make(map[int]struct{}, len(currentIds))
  668. for _, x := range currentIds {
  669. have[x] = struct{}{}
  670. }
  671. clientWire := existing.ToClient()
  672. flow, ffErr := s.EffectiveFlow(nil, id)
  673. if ffErr != nil {
  674. return false, ffErr
  675. }
  676. clientWire.Flow = flow
  677. clientWire.UpdatedAt = time.Now().UnixMilli()
  678. needRestart := false
  679. for _, ibId := range inboundIds {
  680. if _, attached := have[ibId]; attached {
  681. continue
  682. }
  683. inbound, getErr := inboundSvc.GetInbound(ibId)
  684. if getErr != nil {
  685. return needRestart, getErr
  686. }
  687. copyClient := *clientWire
  688. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  689. return needRestart, err
  690. }
  691. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}})
  692. if mErr != nil {
  693. return needRestart, mErr
  694. }
  695. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  696. Id: ibId,
  697. Settings: string(settingsPayload),
  698. })
  699. if addErr != nil {
  700. return needRestart, addErr
  701. }
  702. if nr {
  703. needRestart = true
  704. }
  705. }
  706. return needRestart, nil
  707. }
  708. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  709. return s.Create(inboundSvc, &ClientCreatePayload{
  710. Client: client,
  711. InboundIds: []int{inboundId},
  712. })
  713. }
  714. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  715. if email == "" {
  716. return false, common.NewError("client email is required")
  717. }
  718. rec, err := s.GetRecordByEmail(nil, email)
  719. if err != nil {
  720. return false, err
  721. }
  722. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  723. }
  724. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  725. if email == "" {
  726. return false, common.NewError("client email is required")
  727. }
  728. rec, err := s.GetRecordByEmail(nil, email)
  729. if err != nil {
  730. return false, err
  731. }
  732. return s.Attach(inboundSvc, rec.Id, inboundIds)
  733. }
  734. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  735. if email == "" {
  736. return false, common.NewError("client email is required")
  737. }
  738. rec, err := s.GetRecordByEmail(nil, email)
  739. if err != nil {
  740. return false, err
  741. }
  742. return s.Detach(inboundSvc, rec.Id, inboundIds)
  743. }
  744. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  745. if email == "" {
  746. return false, common.NewError("client email is required")
  747. }
  748. rec, err := s.GetRecordByEmail(nil, email)
  749. if err == nil {
  750. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  751. }
  752. if !errors.Is(err, gorm.ErrRecordNotFound) {
  753. return false, err
  754. }
  755. inboundIds, idsErr := s.findInboundIdsByClientEmail(email)
  756. if idsErr != nil {
  757. return false, idsErr
  758. }
  759. if len(inboundIds) == 0 {
  760. return false, common.NewError(fmt.Sprintf("client %q not found in any inbound or client record", email))
  761. }
  762. needRestart := false
  763. var delErrs []error
  764. for _, ibId := range inboundIds {
  765. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, email, keepTraffic, true)
  766. if delErr != nil {
  767. if errors.Is(delErr, ErrClientNotInInbound) {
  768. continue
  769. }
  770. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, delErr))
  771. continue
  772. }
  773. if nr {
  774. needRestart = true
  775. }
  776. }
  777. if len(delErrs) > 0 {
  778. return needRestart, errors.Join(delErrs...)
  779. }
  780. if !keepTraffic {
  781. db := database.GetDB()
  782. if err := db.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  783. return needRestart, err
  784. }
  785. if err := clearGlobalTraffic(db, email); err != nil {
  786. return needRestart, err
  787. }
  788. if err := db.Where("client_email = ?", email).Delete(&model.InboundClientIps{}).Error; err != nil {
  789. return needRestart, err
  790. }
  791. if err := db.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  792. return needRestart, err
  793. }
  794. }
  795. return needRestart, nil
  796. }
  797. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client, limitHwid int, inboundFilter ...int) (bool, error) {
  798. if email == "" {
  799. return false, common.NewError("client email is required")
  800. }
  801. rec, err := s.GetRecordByEmail(nil, email)
  802. if err != nil {
  803. return false, err
  804. }
  805. return s.Update(inboundSvc, rec.Id, updated, limitHwid, inboundFilter...)
  806. }
  807. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  808. existing, err := s.GetByID(id)
  809. if err != nil {
  810. return false, err
  811. }
  812. currentIds, err := s.GetInboundIdsForRecord(id)
  813. if err != nil {
  814. return false, err
  815. }
  816. have := make(map[int]struct{}, len(currentIds))
  817. for _, x := range currentIds {
  818. have[x] = struct{}{}
  819. }
  820. needRestart := false
  821. for _, ibId := range inboundIds {
  822. if _, attached := have[ibId]; !attached {
  823. continue
  824. }
  825. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  826. return needRestart, getErr
  827. }
  828. // Detach by email — the client's stable identity (see Delete).
  829. if existing.Email == "" {
  830. continue
  831. }
  832. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, true, false)
  833. if delErr != nil {
  834. if errors.Is(delErr, ErrClientNotInInbound) {
  835. continue
  836. }
  837. return needRestart, delErr
  838. }
  839. if nr {
  840. needRestart = true
  841. }
  842. }
  843. return needRestart, nil
  844. }