client_hwid.go 9.0 KB

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