client_crud.go 23 KB

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