client_crud.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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. emailSubIDs, sidErr := inboundSvc.getAllEmailSubIDs()
  178. if sidErr != nil {
  179. return false, sidErr
  180. }
  181. needRestart := false
  182. for _, ibId := range payload.InboundIds {
  183. inbound, getErr := inboundSvc.GetInbound(ibId)
  184. if getErr != nil {
  185. return needRestart, getErr
  186. }
  187. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  188. return needRestart, err
  189. }
  190. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(client, inbound)}})
  191. if mErr != nil {
  192. return needRestart, mErr
  193. }
  194. nr, addErr := s.addInboundClient(inboundSvc, &model.Inbound{
  195. Id: ibId,
  196. Settings: string(settingsPayload),
  197. }, emailSubIDs)
  198. if addErr != nil {
  199. return needRestart, addErr
  200. }
  201. if nr {
  202. needRestart = true
  203. }
  204. }
  205. if err := s.setClientLimitHwidByEmail(nil, client.Email, payload.LimitHwid); err != nil {
  206. return needRestart, err
  207. }
  208. return needRestart, nil
  209. }
  210. func (s *ClientService) fillProtocolDefaults(c *model.Client, ib *model.Inbound) error {
  211. switch ib.Protocol {
  212. case model.VMESS, model.VLESS:
  213. if c.ID == "" {
  214. c.ID = uuid.NewString()
  215. }
  216. case model.Trojan:
  217. if c.Password == "" {
  218. c.Password = strings.ReplaceAll(uuid.NewString(), "-", "")
  219. }
  220. case model.Shadowsocks:
  221. method := shadowsocksMethodFromSettings(ib.Settings)
  222. if c.Password == "" || !validShadowsocksClientKey(method, c.Password) {
  223. c.Password = randomShadowsocksClientKey(method)
  224. }
  225. case model.Hysteria:
  226. if c.Auth == "" {
  227. c.Auth = strings.ReplaceAll(uuid.NewString(), "-", "")
  228. }
  229. case model.MTProto:
  230. if c.Secret == "" {
  231. c.Secret = model.GenerateFakeTLSSecret(mtprotoDomainFromSettings(ib.Settings))
  232. }
  233. }
  234. return nil
  235. }
  236. // defaultMtprotoDomain is the FakeTLS fronting domain used when an mtproto
  237. // inbound carries no fakeTlsDomain of its own; it mirrors the frontend default.
  238. const defaultMtprotoDomain = "www.cloudflare.com"
  239. // mtprotoDomainFromSettings returns the inbound-level FakeTLS domain, falling
  240. // back to the default when unset, so a generated client secret always fronts a
  241. // real hostname.
  242. func mtprotoDomainFromSettings(settings string) string {
  243. domain := ""
  244. if settings != "" {
  245. var m map[string]any
  246. if err := json.Unmarshal([]byte(settings), &m); err == nil {
  247. domain, _ = m["fakeTlsDomain"].(string)
  248. }
  249. }
  250. domain = strings.TrimSpace(domain)
  251. if domain == "" {
  252. return defaultMtprotoDomain
  253. }
  254. return domain
  255. }
  256. func clientWithInboundFlow(c model.Client, ib *model.Inbound) model.Client {
  257. if ib.DisableFlow || !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings) {
  258. c.Flow = ""
  259. }
  260. return c
  261. }
  262. func shadowsocksMethodFromSettings(settings string) string {
  263. if settings == "" {
  264. return ""
  265. }
  266. var m map[string]any
  267. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  268. return ""
  269. }
  270. method, _ := m["method"].(string)
  271. return method
  272. }
  273. func randomShadowsocksClientKey(method string) string {
  274. if n := shadowsocksKeyBytes(method); n > 0 {
  275. return random.Base64Bytes(n)
  276. }
  277. return strings.ReplaceAll(uuid.NewString(), "-", "")
  278. }
  279. func validShadowsocksClientKey(method, key string) bool {
  280. n := shadowsocksKeyBytes(method)
  281. if n == 0 {
  282. return key != ""
  283. }
  284. decoded, err := base64.StdEncoding.DecodeString(key)
  285. if err != nil {
  286. return false
  287. }
  288. return len(decoded) == n
  289. }
  290. func shadowsocksKeyBytes(method string) int {
  291. switch method {
  292. case "2022-blake3-aes-128-gcm":
  293. return 16
  294. case "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305":
  295. return 32
  296. }
  297. return 0
  298. }
  299. // normalizeShadowsocksClientKeys rewrites any Shadowsocks-2022 client password
  300. // whose decoded length no longer matches settings.method, which happens after the
  301. // inbound method is switched between ciphers of different key sizes (e.g.
  302. // aes-256↔aes-128). A wrong-length uPSK makes xray reject the user, so the link
  303. // fails to connect; regenerating restores a valid key (clients must re-fetch).
  304. // Non-Shadowsocks / legacy-SS settings pass through unchanged.
  305. func normalizeShadowsocksClientKeys(settings string) (string, bool) {
  306. method := shadowsocksMethodFromSettings(settings)
  307. if shadowsocksKeyBytes(method) == 0 {
  308. return settings, false
  309. }
  310. var m map[string]any
  311. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  312. return settings, false
  313. }
  314. clients, ok := m["clients"].([]any)
  315. if !ok {
  316. return settings, false
  317. }
  318. changed := false
  319. for i := range clients {
  320. c, ok := clients[i].(map[string]any)
  321. if !ok {
  322. continue
  323. }
  324. if pw, _ := c["password"].(string); validShadowsocksClientKey(method, pw) {
  325. continue
  326. }
  327. c["password"] = randomShadowsocksClientKey(method)
  328. clients[i] = c
  329. changed = true
  330. }
  331. if !changed {
  332. return settings, false
  333. }
  334. m["clients"] = clients
  335. bs, err := json.MarshalIndent(m, "", " ")
  336. if err != nil {
  337. return settings, false
  338. }
  339. return string(bs), true
  340. }
  341. func applyShadowsocksClientMethod(clients []any, settings map[string]any) {
  342. method, _ := settings["method"].(string)
  343. is2022 := strings.HasPrefix(method, "2022-blake3-")
  344. for i := range clients {
  345. cm, ok := clients[i].(map[string]any)
  346. if !ok {
  347. continue
  348. }
  349. if is2022 {
  350. if _, hasKey := cm["method"]; hasKey {
  351. delete(cm, "method")
  352. clients[i] = cm
  353. }
  354. continue
  355. }
  356. if method == "" {
  357. continue
  358. }
  359. if existing, _ := cm["method"].(string); existing != "" {
  360. continue
  361. }
  362. cm["method"] = method
  363. clients[i] = cm
  364. }
  365. }
  366. func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model.Client, limitHwid int, inboundFilter ...int) (bool, error) {
  367. existing, err := s.GetByID(id)
  368. if err != nil {
  369. return false, err
  370. }
  371. inboundIds, err := s.GetInboundIdsForRecord(id)
  372. if err != nil {
  373. return false, err
  374. }
  375. if len(inboundFilter) > 0 {
  376. allow := make(map[int]struct{}, len(inboundFilter))
  377. for _, fid := range inboundFilter {
  378. allow[fid] = struct{}{}
  379. }
  380. filtered := inboundIds[:0:0]
  381. for _, ibId := range inboundIds {
  382. if _, ok := allow[ibId]; ok {
  383. filtered = append(filtered, ibId)
  384. }
  385. }
  386. inboundIds = filtered
  387. }
  388. if strings.TrimSpace(updated.Email) == "" {
  389. return false, common.NewError("client email is required")
  390. }
  391. if err := validateClientEmail(updated.Email); err != nil {
  392. return false, err
  393. }
  394. if err := validateClientSubID(updated.SubID); err != nil {
  395. return false, err
  396. }
  397. if err := validateClientResetDay(updated.ResetDay); err != nil {
  398. return false, err
  399. }
  400. if err := validateClientResetMax(updated.ResetMax); err != nil {
  401. return false, err
  402. }
  403. if err := validateClientTrafficReset(updated.TrafficReset, updated.TrafficResetDay); err != nil {
  404. return false, err
  405. }
  406. normalizeClientTrafficReset(&updated)
  407. if updated.SubID == "" {
  408. updated.SubID = existing.SubID
  409. }
  410. if updated.SubID == "" {
  411. updated.SubID = uuid.NewString()
  412. }
  413. updated.UpdatedAt = time.Now().UnixMilli()
  414. if updated.CreatedAt == 0 {
  415. updated.CreatedAt = existing.CreatedAt
  416. }
  417. // Preserve existing credentials when the caller omits them, so a partial
  418. // update (e.g. only changing traffic/expiry) doesn't silently rotate the
  419. // client's UUID/password/auth via fillProtocolDefaults. Supplying a new
  420. // value still rotates it intentionally.
  421. if updated.ID == "" {
  422. updated.ID = existing.UUID
  423. }
  424. if updated.Password == "" {
  425. updated.Password = existing.Password
  426. }
  427. if updated.Auth == "" {
  428. updated.Auth = existing.Auth
  429. }
  430. if updated.Secret == "" {
  431. updated.Secret = existing.Secret
  432. }
  433. if updated.Email != existing.Email {
  434. var collisionCount int64
  435. if err := database.GetDB().Model(&model.ClientRecord{}).
  436. Where("email = ? AND id <> ?", updated.Email, id).
  437. Count(&collisionCount).Error; err != nil {
  438. return false, err
  439. }
  440. if collisionCount > 0 {
  441. return false, common.NewError("Duplicate email:", updated.Email)
  442. }
  443. }
  444. if updated.SubID != existing.SubID {
  445. var subCollision int64
  446. if err := database.GetDB().Model(&model.ClientRecord{}).
  447. Where("sub_id = ? AND id <> ?", updated.SubID, id).
  448. Count(&subCollision).Error; err != nil {
  449. return false, err
  450. }
  451. if subCollision > 0 {
  452. return false, common.NewError("Duplicate subId:", updated.SubID)
  453. }
  454. }
  455. needRestart := false
  456. for _, ibId := range inboundIds {
  457. inbound, getErr := inboundSvc.GetInbound(ibId)
  458. if getErr != nil {
  459. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  460. if err := database.GetDB().
  461. Where("client_id = ? AND inbound_id = ?", id, ibId).
  462. Delete(&model.ClientInbound{}).Error; err != nil {
  463. return needRestart, err
  464. }
  465. continue
  466. }
  467. return needRestart, getErr
  468. }
  469. if existing.Email == "" {
  470. continue
  471. }
  472. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  473. return needRestart, err
  474. }
  475. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(updated, inbound)}})
  476. if mErr != nil {
  477. return needRestart, mErr
  478. }
  479. nr, upErr := s.UpdateInboundClient(inboundSvc, &model.Inbound{
  480. Id: ibId,
  481. Settings: string(settingsPayload),
  482. }, existing.Email)
  483. if upErr != nil {
  484. return needRestart, upErr
  485. }
  486. if nr {
  487. needRestart = true
  488. }
  489. }
  490. // UpdateInboundClient renames the record atomically with each inbound's
  491. // settings JSON; this direct write only covers records with no inbound left.
  492. if updated.Email != existing.Email {
  493. if err := database.GetDB().Model(&model.ClientRecord{}).
  494. Where("id = ? AND email = ?", id, existing.Email).
  495. Update("email", updated.Email).Error; err != nil {
  496. return needRestart, err
  497. }
  498. }
  499. if len(inboundIds) == 0 {
  500. merged := *existing
  501. applyClientRecordMerge(&merged, updated.ToRecord())
  502. if err := database.GetDB().Model(&model.ClientRecord{}).
  503. Where("id = ?", id).
  504. Updates(map[string]any{
  505. "sub_id": merged.SubID,
  506. "uuid": merged.UUID,
  507. "password": merged.Password,
  508. "auth": merged.Auth,
  509. "secret": merged.Secret,
  510. "flow": merged.Flow,
  511. "security": merged.Security,
  512. "wg_private_key": merged.PrivateKey,
  513. "wg_public_key": merged.PublicKey,
  514. "wg_allowed_ips": merged.AllowedIPs,
  515. "wg_pre_shared_key": merged.PreSharedKey,
  516. "wg_keep_alive": merged.KeepAlive,
  517. "limit_ip": merged.LimitIP,
  518. "total_gb": merged.TotalGB,
  519. "expiry_time": merged.ExpiryTime,
  520. "tg_id": merged.TgID,
  521. "comment": merged.Comment,
  522. "reset": merged.Reset,
  523. "reset_day": merged.ResetDay,
  524. "reset_max": merged.ResetMax,
  525. "traffic_reset": merged.TrafficReset,
  526. "traffic_reset_day": merged.TrafficResetDay,
  527. }).Error; err != nil {
  528. return needRestart, err
  529. }
  530. }
  531. reverseStr := ""
  532. if updated.Reverse != nil && strings.TrimSpace(updated.Reverse.Tag) != "" {
  533. if b, mErr := json.Marshal(updated.Reverse); mErr == nil {
  534. reverseStr = string(b)
  535. }
  536. }
  537. if err := database.GetDB().Model(&model.ClientRecord{}).
  538. Where("id = ?", id).
  539. Update("reverse", reverseStr).Error; err != nil {
  540. return needRestart, err
  541. }
  542. // Persist the group explicitly. SyncInbound deliberately preserves the
  543. // stored group when the inbound settings carry none — so a node snapshot or a
  544. // group-less settings rebuild can't wipe it (see SyncInbound + its tests).
  545. // That guard also meant clearing the group in the client editor never took
  546. // effect. The editor always round-trips the field, so apply it here,
  547. // including the empty string that removes the client from its group.
  548. if err := database.GetDB().Model(&model.ClientRecord{}).
  549. Where("id = ?", id).
  550. UpdateColumn("group_name", updated.Group).Error; err != nil {
  551. return needRestart, err
  552. }
  553. // Same shape as the group write above: SyncInbound keeps a stored ad-tag
  554. // when the incoming settings carry none, so clearing the override must be
  555. // applied here, where the editor always round-trips the field.
  556. if err := database.GetDB().Model(&model.ClientRecord{}).
  557. Where("id = ?", id).
  558. UpdateColumn("ad_tag", updated.AdTag).Error; err != nil {
  559. return needRestart, err
  560. }
  561. if err := database.GetDB().Model(&model.ClientRecord{}).
  562. Where("id = ?", id).
  563. UpdateColumn("enable", updated.Enable).Error; err != nil {
  564. return needRestart, err
  565. }
  566. if err := s.setClientLimitHwidByEmail(nil, updated.Email, limitHwid); err != nil {
  567. return needRestart, err
  568. }
  569. if err := database.GetDB().Model(&model.ClientRecord{}).
  570. Where("id = ?", id).
  571. UpdateColumn("updated_at", time.Now().UnixMilli()).Error; err != nil {
  572. return needRestart, err
  573. }
  574. return needRestart, nil
  575. }
  576. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  577. existing, err := s.GetByID(id)
  578. if err != nil {
  579. return false, err
  580. }
  581. tombstoneClientEmail(existing.Email)
  582. inboundIds, err := s.GetInboundIdsForRecord(id)
  583. if err != nil {
  584. withdrawClientTombstones(existing.Email)
  585. return false, err
  586. }
  587. needRestart := false
  588. var delErrs []error
  589. for _, ibId := range inboundIds {
  590. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  591. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  592. continue
  593. }
  594. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, getErr))
  595. continue
  596. }
  597. // Always delete by email — the client's stable identity. This removes
  598. // every matching entry from the inbound's settings even when the stored
  599. // credential (UUID/password/auth) drifted from the inbound JSON, or a
  600. // duplicate entry with the same email exists.
  601. if existing.Email == "" {
  602. continue
  603. }
  604. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, keepTraffic, true)
  605. if delErr != nil {
  606. // The client is already absent from this inbound (data drift or a
  607. // retried delete). Skip it — deletion stays idempotent.
  608. if errors.Is(delErr, ErrClientNotInInbound) {
  609. continue
  610. }
  611. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, delErr))
  612. continue
  613. }
  614. if nr {
  615. needRestart = true
  616. }
  617. }
  618. // A failed inbound still holds the client in its settings JSON: keep the
  619. // record so the next delete retries exactly the leftovers, and report it.
  620. // The tombstone lifts with it, or the next node merge finishes the deletion.
  621. if len(delErrs) > 0 {
  622. withdrawClientTombstones(existing.Email)
  623. return needRestart, errors.Join(delErrs...)
  624. }
  625. db := database.GetDB()
  626. if err := db.Transaction(func(tx *gorm.DB) error {
  627. if existing.Email != "" {
  628. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{existing.Email}); err != nil {
  629. return err
  630. }
  631. }
  632. if err := tx.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  633. return err
  634. }
  635. if err := tx.Where("client_id = ?", id).Delete(&model.ClientExternalLink{}).Error; err != nil {
  636. return err
  637. }
  638. if err := clearClientHwidsBySubIDTx(tx, existing.SubID); err != nil {
  639. return err
  640. }
  641. if !keepTraffic && existing.Email != "" {
  642. if err := tx.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  643. return err
  644. }
  645. if err := clearGlobalTraffic(tx, existing.Email); err != nil {
  646. return err
  647. }
  648. if err := tx.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  649. return err
  650. }
  651. if err := tx.Where("email = ?", existing.Email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  652. return err
  653. }
  654. }
  655. return tx.Delete(&model.ClientRecord{}, id).Error
  656. }); err != nil {
  657. withdrawClientTombstones(existing.Email)
  658. return needRestart, err
  659. }
  660. return needRestart, nil
  661. }
  662. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  663. existing, err := s.GetByID(id)
  664. if err != nil {
  665. return false, err
  666. }
  667. currentIds, err := s.GetInboundIdsForRecord(id)
  668. if err != nil {
  669. return false, err
  670. }
  671. have := make(map[int]struct{}, len(currentIds))
  672. for _, x := range currentIds {
  673. have[x] = struct{}{}
  674. }
  675. clientWire := existing.ToClient()
  676. flow, ffErr := s.EffectiveFlow(nil, id)
  677. if ffErr != nil {
  678. return false, ffErr
  679. }
  680. clientWire.Flow = flow
  681. clientWire.UpdatedAt = time.Now().UnixMilli()
  682. emailSubIDs, sidErr := inboundSvc.getAllEmailSubIDs()
  683. if sidErr != nil {
  684. return false, sidErr
  685. }
  686. needRestart := false
  687. for _, ibId := range inboundIds {
  688. if _, attached := have[ibId]; attached {
  689. continue
  690. }
  691. inbound, getErr := inboundSvc.GetInbound(ibId)
  692. if getErr != nil {
  693. return needRestart, getErr
  694. }
  695. copyClient := *clientWire
  696. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  697. return needRestart, err
  698. }
  699. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}})
  700. if mErr != nil {
  701. return needRestart, mErr
  702. }
  703. nr, addErr := s.addInboundClient(inboundSvc, &model.Inbound{
  704. Id: ibId,
  705. Settings: string(settingsPayload),
  706. }, emailSubIDs)
  707. if addErr != nil {
  708. return needRestart, addErr
  709. }
  710. if nr {
  711. needRestart = true
  712. }
  713. }
  714. return needRestart, nil
  715. }
  716. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  717. return s.Create(inboundSvc, &ClientCreatePayload{
  718. Client: client,
  719. InboundIds: []int{inboundId},
  720. })
  721. }
  722. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  723. if email == "" {
  724. return false, common.NewError("client email is required")
  725. }
  726. rec, err := s.GetRecordByEmail(nil, email)
  727. if err != nil {
  728. return false, err
  729. }
  730. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  731. }
  732. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  733. if email == "" {
  734. return false, common.NewError("client email is required")
  735. }
  736. rec, err := s.GetRecordByEmail(nil, email)
  737. if err != nil {
  738. return false, err
  739. }
  740. return s.Attach(inboundSvc, rec.Id, inboundIds)
  741. }
  742. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  743. if email == "" {
  744. return false, common.NewError("client email is required")
  745. }
  746. rec, err := s.GetRecordByEmail(nil, email)
  747. if err != nil {
  748. return false, err
  749. }
  750. return s.Detach(inboundSvc, rec.Id, inboundIds)
  751. }
  752. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  753. if email == "" {
  754. return false, common.NewError("client email is required")
  755. }
  756. rec, err := s.GetRecordByEmail(nil, email)
  757. if err == nil {
  758. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  759. }
  760. if !errors.Is(err, gorm.ErrRecordNotFound) {
  761. return false, err
  762. }
  763. inboundIds, idsErr := s.findInboundIdsByClientEmail(email)
  764. if idsErr != nil {
  765. return false, idsErr
  766. }
  767. if len(inboundIds) == 0 {
  768. return false, common.NewError(fmt.Sprintf("client %q not found in any inbound or client record", email))
  769. }
  770. needRestart := false
  771. var delErrs []error
  772. for _, ibId := range inboundIds {
  773. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, email, keepTraffic, true)
  774. if delErr != nil {
  775. if errors.Is(delErr, ErrClientNotInInbound) {
  776. continue
  777. }
  778. delErrs = append(delErrs, fmt.Errorf("inbound %d: %w", ibId, delErr))
  779. continue
  780. }
  781. if nr {
  782. needRestart = true
  783. }
  784. }
  785. if len(delErrs) > 0 {
  786. return needRestart, errors.Join(delErrs...)
  787. }
  788. if !keepTraffic {
  789. db := database.GetDB()
  790. if err := db.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  791. return needRestart, err
  792. }
  793. if err := clearGlobalTraffic(db, email); err != nil {
  794. return needRestart, err
  795. }
  796. if err := db.Where("client_email = ?", email).Delete(&model.InboundClientIps{}).Error; err != nil {
  797. return needRestart, err
  798. }
  799. if err := db.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  800. return needRestart, err
  801. }
  802. }
  803. return needRestart, nil
  804. }
  805. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client, limitHwid int, inboundFilter ...int) (bool, error) {
  806. if email == "" {
  807. return false, common.NewError("client email is required")
  808. }
  809. rec, err := s.GetRecordByEmail(nil, email)
  810. if err != nil {
  811. return false, err
  812. }
  813. return s.Update(inboundSvc, rec.Id, updated, limitHwid, inboundFilter...)
  814. }
  815. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  816. existing, err := s.GetByID(id)
  817. if err != nil {
  818. return false, err
  819. }
  820. currentIds, err := s.GetInboundIdsForRecord(id)
  821. if err != nil {
  822. return false, err
  823. }
  824. have := make(map[int]struct{}, len(currentIds))
  825. for _, x := range currentIds {
  826. have[x] = struct{}{}
  827. }
  828. needRestart := false
  829. for _, ibId := range inboundIds {
  830. if _, attached := have[ibId]; !attached {
  831. continue
  832. }
  833. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  834. return needRestart, getErr
  835. }
  836. // Detach by email — the client's stable identity (see Delete).
  837. if existing.Email == "" {
  838. continue
  839. }
  840. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, true, false)
  841. if delErr != nil {
  842. if errors.Is(delErr, ErrClientNotInInbound) {
  843. continue
  844. }
  845. return needRestart, delErr
  846. }
  847. if nr {
  848. needRestart = true
  849. }
  850. }
  851. return needRestart, nil
  852. }