client_crud.go 21 KB

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