client_hwid.go 10.0 KB

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