client_hwid.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. package service
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "errors"
  6. "strings"
  7. "time"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  10. "gorm.io/gorm"
  11. )
  12. type HwidRequest struct {
  13. Hwid string
  14. UserAgent string
  15. DeviceOS string
  16. OsVersion string
  17. DeviceModel string
  18. }
  19. type HwidGateResult struct {
  20. Allowed bool
  21. Active bool
  22. NotSupported bool
  23. MaxDevicesReached bool
  24. LimitReached bool
  25. Limit int
  26. Registered int
  27. }
  28. // HwidSlotStatus is the aggregate device-slot view exposed to subscribers:
  29. // counters only, no hwid value or hash, no email, no device metadata.
  30. type HwidSlotStatus struct {
  31. Active bool `json:"active" example:"true"`
  32. Limit int `json:"limit" example:"2"`
  33. Registered int `json:"registered" example:"1"`
  34. Remaining int `json:"remaining" example:"1"`
  35. Full bool `json:"full" example:"false"`
  36. }
  37. const minHwidLength = 6
  38. type ClientHwidInfo struct {
  39. Id int `json:"id"`
  40. FirstSeen int64 `json:"firstSeen"`
  41. LastSeen int64 `json:"lastSeen"`
  42. UserAgent string `json:"userAgent"`
  43. DeviceOS string `json:"deviceOs"`
  44. OsVersion string `json:"osVersion"`
  45. DeviceModel string `json:"deviceModel"`
  46. }
  47. func hashHwid(raw string) string {
  48. sum := sha256.Sum256([]byte(raw))
  49. return hex.EncodeToString(sum[:])
  50. }
  51. func trimHwidMeta(s string) string {
  52. s = strings.TrimSpace(s)
  53. r := []rune(s)
  54. if len(r) > 512 {
  55. return string(r[:512])
  56. }
  57. return s
  58. }
  59. func normalizeHwidRequest(req HwidRequest) HwidRequest {
  60. return HwidRequest{
  61. Hwid: strings.TrimSpace(req.Hwid),
  62. UserAgent: trimHwidMeta(req.UserAgent),
  63. DeviceOS: trimHwidMeta(req.DeviceOS),
  64. OsVersion: trimHwidMeta(req.OsVersion),
  65. DeviceModel: trimHwidMeta(req.DeviceModel),
  66. }
  67. }
  68. func effectiveHwidLimitForSubID(tx *gorm.DB, subID string) (int, error) {
  69. var limit int
  70. err := tx.Model(&model.ClientRecord{}).
  71. Where("sub_id = ? AND enable = ?", subID, true).
  72. Select("COALESCE(MAX(limit_hwid), 0)").
  73. Scan(&limit).Error
  74. return limit, err
  75. }
  76. func (s *ClientService) EnforceHwidForSubID(subID string, req HwidRequest) (HwidGateResult, error) {
  77. var res HwidGateResult
  78. subID = strings.TrimSpace(subID)
  79. if subID == "" {
  80. res.Allowed = true
  81. return res, nil
  82. }
  83. db := database.GetDB()
  84. limit, err := effectiveHwidLimitForSubID(db, subID)
  85. if err != nil {
  86. return res, err
  87. }
  88. if limit <= 0 {
  89. res.Allowed = true
  90. return res, nil
  91. }
  92. req = normalizeHwidRequest(req)
  93. res.Active = true
  94. res.Limit = limit
  95. if len(req.Hwid) < minHwidLength {
  96. res.NotSupported = true
  97. return res, nil
  98. }
  99. hwidHash := hashHwid(req.Hwid)
  100. err = db.Transaction(func(tx *gorm.DB) error {
  101. limit, err := effectiveHwidLimitForSubID(tx, subID)
  102. if err != nil {
  103. return err
  104. }
  105. if limit <= 0 {
  106. res = HwidGateResult{Allowed: true}
  107. return nil
  108. }
  109. res.Active = true
  110. res.Limit = limit
  111. now := time.Now().UnixMilli()
  112. var existing model.ClientHwid
  113. err = tx.Where("sub_id = ? AND hwid_hash = ?", subID, hwidHash).First(&existing).Error
  114. if err == nil {
  115. if err := tx.Model(&model.ClientHwid{}).Where("id = ?", existing.Id).Updates(map[string]any{
  116. "last_seen": now, "user_agent": req.UserAgent, "device_os": req.DeviceOS, "os_version": req.OsVersion, "device_model": req.DeviceModel,
  117. }).Error; err != nil {
  118. return err
  119. }
  120. var count int64
  121. if err := tx.Model(&model.ClientHwid{}).Where("sub_id = ?", subID).Count(&count).Error; err != nil {
  122. return err
  123. }
  124. res.Allowed = true
  125. res.Registered = int(count)
  126. res.LimitReached = count >= int64(limit)
  127. return nil
  128. }
  129. if !errors.Is(err, gorm.ErrRecordNotFound) {
  130. return err
  131. }
  132. var count int64
  133. if err := tx.Model(&model.ClientHwid{}).Where("sub_id = ?", subID).Count(&count).Error; err != nil {
  134. return err
  135. }
  136. res.Registered = int(count)
  137. if count >= int64(limit) {
  138. res.MaxDevicesReached = true
  139. res.LimitReached = true
  140. return nil
  141. }
  142. if err := tx.Create(&model.ClientHwid{SubID: subID, HwidHash: hwidHash, FirstSeen: now, LastSeen: now, UserAgent: req.UserAgent, DeviceOS: req.DeviceOS, OsVersion: req.OsVersion, DeviceModel: req.DeviceModel}).Error; err != nil {
  143. return err
  144. }
  145. res.Allowed = true
  146. res.Registered = int(count) + 1
  147. res.LimitReached = res.Registered >= limit
  148. return nil
  149. })
  150. return res, err
  151. }
  152. // HwidSlotStatusForSubID is SELECT-only: it must never write client_hwids or
  153. // last_seen. Enabled-clients scope mirrors the gate, so limit == limit enforced.
  154. func (s *ClientService) HwidSlotStatusForSubID(subID string) (status HwidSlotStatus, found bool, err error) {
  155. subID = strings.TrimSpace(subID)
  156. if subID == "" {
  157. return status, false, nil
  158. }
  159. db := database.GetDB()
  160. var enabled int64
  161. if err := db.Model(&model.ClientRecord{}).
  162. Where("sub_id = ? AND enable = ?", subID, true).
  163. Count(&enabled).Error; err != nil {
  164. return status, false, err
  165. }
  166. if enabled == 0 {
  167. return status, false, nil
  168. }
  169. limit, err := effectiveHwidLimitForSubID(db, subID)
  170. if err != nil {
  171. return status, false, err
  172. }
  173. if limit <= 0 {
  174. return status, true, nil
  175. }
  176. var registered int64
  177. if err := db.Model(&model.ClientHwid{}).Where("sub_id = ?", subID).Count(&registered).Error; err != nil {
  178. return status, false, err
  179. }
  180. status.Active = true
  181. status.Limit = limit
  182. status.Registered = int(registered)
  183. status.Remaining = max(limit-status.Registered, 0)
  184. status.Full = status.Registered >= limit
  185. return status, true, nil
  186. }
  187. func (s *ClientService) ListClientHwids(email string) ([]ClientHwidInfo, error) {
  188. rec, err := s.GetRecordByEmail(nil, email)
  189. if err != nil {
  190. return nil, err
  191. }
  192. subID := strings.TrimSpace(rec.SubID)
  193. if subID == "" {
  194. return nil, nil
  195. }
  196. var rows []model.ClientHwid
  197. if err := database.GetDB().
  198. Where("sub_id = ?", subID).
  199. Order("last_seen DESC").
  200. Order("id DESC").
  201. Find(&rows).Error; err != nil {
  202. return nil, err
  203. }
  204. out := make([]ClientHwidInfo, 0, len(rows))
  205. for _, r := range rows {
  206. out = append(out, ClientHwidInfo{
  207. Id: r.Id,
  208. FirstSeen: r.FirstSeen,
  209. LastSeen: r.LastSeen,
  210. UserAgent: r.UserAgent,
  211. DeviceOS: r.DeviceOS,
  212. OsVersion: r.OsVersion,
  213. DeviceModel: r.DeviceModel,
  214. })
  215. }
  216. return out, nil
  217. }
  218. func (s *ClientService) ClearClientHwids(email string) error {
  219. rec, err := s.GetRecordByEmail(nil, email)
  220. if err != nil {
  221. return err
  222. }
  223. subID := strings.TrimSpace(rec.SubID)
  224. if subID == "" {
  225. return nil
  226. }
  227. return database.GetDB().Where("sub_id = ?", subID).Delete(&model.ClientHwid{}).Error
  228. }
  229. // DeleteClientHwid removes one device, scoped to the client's sub_id: ids
  230. // are a global auto-increment, so an id outside this subscription won't match.
  231. func (s *ClientService) DeleteClientHwid(email string, id int) error {
  232. rec, err := s.GetRecordByEmail(nil, email)
  233. if err != nil {
  234. return err
  235. }
  236. subID := strings.TrimSpace(rec.SubID)
  237. if subID == "" {
  238. return errors.New("client has no subscription id")
  239. }
  240. res := database.GetDB().Where("sub_id = ? AND id = ?", subID, id).Delete(&model.ClientHwid{})
  241. if res.Error != nil {
  242. return res.Error
  243. }
  244. if res.RowsAffected == 0 {
  245. return errors.New("device not found")
  246. }
  247. return nil
  248. }
  249. func (s *ClientService) setClientLimitHwidByEmail(tx *gorm.DB, email string, limit int) error {
  250. if tx == nil {
  251. tx = database.GetDB()
  252. }
  253. if limit < 0 {
  254. limit = 0
  255. }
  256. var rec model.ClientRecord
  257. if err := tx.Where("email = ?", email).First(&rec).Error; err != nil {
  258. return err
  259. }
  260. if err := tx.Model(&model.ClientRecord{}).Where("id = ?", rec.Id).UpdateColumn("limit_hwid", limit).Error; err != nil {
  261. return err
  262. }
  263. subID := strings.TrimSpace(rec.SubID)
  264. if subID == "" {
  265. return nil
  266. }
  267. effective, err := effectiveHwidLimitForSubID(tx, subID)
  268. if err != nil {
  269. return err
  270. }
  271. return trimClientHwidsForSubID(tx, subID, effective)
  272. }
  273. func trimClientHwidsForSubID(tx *gorm.DB, subID string, limit int) error {
  274. subID = strings.TrimSpace(subID)
  275. if subID == "" || limit <= 0 {
  276. return nil
  277. }
  278. var keep []int
  279. if err := tx.Model(&model.ClientHwid{}).
  280. Where("sub_id = ?", subID).
  281. Order("last_seen DESC").
  282. Order("id DESC").
  283. Limit(limit).
  284. Pluck("id", &keep).Error; err != nil {
  285. return err
  286. }
  287. if len(keep) == 0 {
  288. return tx.Where("sub_id = ?", subID).Delete(&model.ClientHwid{}).Error
  289. }
  290. return tx.Where("sub_id = ? AND id NOT IN ?", subID, keep).Delete(&model.ClientHwid{}).Error
  291. }
  292. func clearClientHwidsBySubIDTx(tx *gorm.DB, subIDs ...string) error {
  293. if tx == nil {
  294. tx = database.GetDB()
  295. }
  296. clean := make([]string, 0, len(subIDs))
  297. seen := map[string]struct{}{}
  298. for _, subID := range subIDs {
  299. subID = strings.TrimSpace(subID)
  300. if subID == "" {
  301. continue
  302. }
  303. if _, ok := seen[subID]; ok {
  304. continue
  305. }
  306. seen[subID] = struct{}{}
  307. clean = append(clean, subID)
  308. }
  309. for _, batch := range chunkStrings(clean, sqlInChunk) {
  310. if err := tx.Where("sub_id IN ?", batch).Delete(&model.ClientHwid{}).Error; err != nil {
  311. return err
  312. }
  313. }
  314. return nil
  315. }